缓存数据的类型
在设计缓存的数据时,可以缓存以下类型的数据
-
缓存数值
例如:验证码或用户状态等
如:captcha_bceaf982-3fcc-4153-83e1-0efe1d67e965: egr4
-
数据库查询记录
-
Caching at the object level以数据库对象的角度考虑, 应用更普遍
例如, 用户的基本信息
user = User.query.filter_by(id=1).first() user -> User对象 { 'user_id':1, 'user_name': 'python', 'age': 28, 'introduction': '' }
-
Caching at the database query level以数据库查询的角度考虑,应用场景较特殊,一般仅针对较复杂的查询进行使用
query_result = User.query.join(User.profile).filter_by(id=1).first() -> sql = "select a.user_id, a.user_name, b.gender, b.birthday from tbl_user as a inner join tbl_profile as b on a.user_id=b.user_id where a.user_id=1;" # hash算法 md5 query = md5(sql) # 'fwoifhwoiehfiowy23982f92h929y3209hf209fh2' # redis setex(query, expiry, json.dumps(query_result))
-
-
视图的响应结果(JSON)
@route('/articles')
@cache(exipry=30*60)
def get_articles():
ch = request.args.get('ch')
articles = Article.query.all()
for article in articles:
user = User.query.filter_by(id=article.user_id).first()
comment = Comment.query.filter_by(article_id=article.id).all()
results = {...} # 格式化输出
return results
# redis
# '/artciels?ch=1': json.dumps(results)
@route('/articles')
@cache(exipry=30*60)
def get_articles():
ch = request.args.get('ch')
articles = Article.query.all()
for article in articles:
user = User.query.filter_by(id=article.user_id).first()
comment = Comment.query.all()
results = {...}
return render_template('article_temp', results)
# redis
# '/artciels?ch=1': html