I am a thoughtful program ape, a lifelong learning practitioner, currently serving as team lead in an entrepreneurial team. The technology stack involves Android, Python, Java and Go, which is also the main technology stack of our team. Github: github.com/hylinux1024 wechat official account: AngryCode
0x00 Configure the cache service
Almost all applications now use caching technology, and Redis is the preferred technology for many caching implementations on the server side.
For our application, we also need to use caching technology to improve interface access speed.
First install Redis and start the Redis service.
Download and compile the installation
Wget http://download.redis.io/releases/redis-5.0.5.tar.gz tar XZF redis - 5.0.5. Tar. GzcdRedis - 5.0.5 makeCopy the code
Start the service
src/redis-server
Copy the code
Use the Redis command line client connection test
src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"
Copy the code
You are advised to refer to related official documents for detailed configuration. The focus of this article is on use in projects.
Install dependencies
The installation
pip install redis
Copy the code
(Of course, you can also use flask-cache, which is quite handy, but this article continues with some of the previous code and uses the redis library directly.)
Then make a simple encapsulation of Redis, namely create instance, set cache and get cache altogether three static methods.
import redis
import json
import datetime
Create a connection pool
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
class Redis:
@staticmethod
def connect(db=0):
"" library 0 is used by default.
r = redis.Redis(connection_pool=pool, db=db)
return r
# Convert binary memory data to text stream via serial number and store in Redis
@staticmethod
def set(r, key: str, data, ex=None):
r.set(key, json.dumps(data, cls=CJsonEncoder), ex=ex)
Read the text stream from Redis and deserialize it
@staticmethod
def get(r, key: str):
data = r.get(key)
if data is None:
return None
return json.loads(data)
Copy the code
To get an instance of Redis in a module that requires caching, do the following
r_cache = redis_helper.Redis.connect(db=5)
Copy the code
Since THERE are other services under development on my machine, I choose library 5 as cache to avoid conflicts with other services.
0x01 Representation of entity relationships in SQLAlchemy
The previous lectures did not give a detailed description of how relationships in a model are represented in SQLAlchemy, so today we will break them down.
We illustrate this with the user table (UserInfo) and the authorization table (UserAuth).
class UserInfo(db.Model):
"""Basic User Information"""
__tablename__ = 'user_info'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(64)) # email
nickname = db.Column(db.String(64))
phone = db.Column(db.String(16))
gender = db.Column(db.Integer) # 1 Male 2 female 0 Unknown. class UserAuth(db.Model):"""Authorized Login Form"""
__tablename__ = 'user_auth'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('user_info.id'))
user_basic = db.relationship(UserInfo, backref=db.backref('user_auth', uselist=False))
...
Copy the code
UserInfo has a one-to-one relationship with UserAuth. That is, one user corresponds to one authorization message, and the relationship is represented in SQLAlchemy using the db.relationship() interface
Db.foreignkey (‘user_info.id’)) is required to define the ForeignKey user_id in UserAuth, indicating that it is associated with the id field in the user_info table. These two tables are associated by foreign keys, but in the actual development and use, we hope that when we query the UserAuth instance, we hope to be able to get the instance of the corresponding user information UserInfo directly, then we can use db.relationship() interface. This relationship is specified in UserAuth
user_basic = db.relationship(UserInfo, backref=db.backref('user_auth', uselist=False))
Copy the code
A user_BASIC field is defined in the UserAuth entity. When the UserAuth instance is queried, the UserInfo information can be directly obtained without the program using the foreign key user_id to query user information in the database.
The first argument in db.relationship() indicates which table to associate, and can pass a string of class or table names; The second parameter backref means that UserInfo also defines a user_auth attribute, which can be used to obtain the corresponding authorization information when the user information is queried. Uselist =False means that user_auth and user_info are one-to-one. If there is a one-to-many relationship, uselist=True. If no argument is passed, uselist is True.
0 x03 summary
This article is a supplement to the representations of relationships and the use of caching in model definitions covered in previous lectures.
0 x04 reference
- Flask-sqlalchemy.palletsprojects.com/en/2.x/mode…
- redis.io/download