Flaskページデータをredisにキャッシュ
2482 ワード
コアはpickleを用いてデータをシーケンス化し,文字ストリームでredisにキャッシュし,使用するときに取り出して逆シーケンス化する.
import redis
from datetime import datetime
from flask import session,request
from ..models import db
import pickle
class Redis:
@staticmethod
def connect():
r = redis.StrictRedis(host='localhost', port=6379, db=0)
return r
# , redis
@staticmethod
def set_data(r,key,data,ex=None):
r.set(key,pickle.dumps(data),ex)
# redis ,
@staticmethod
def get_data(r,key):
data = r.get(key)
if data is None:
return None
return pickle.loads(data)
@home.route('/detail/')
def detail(id):
today = datetime.now().date()
list_goods = None
# ,
cached_redis_remark = ""
r = Redis.connect()
#
key = "data-cached:detail-id-%d" % (id)
# redis ( , None)
goods = Redis.get_data(r, key)
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS'] and goods:
# flash(" ")
cached_redis_remark += "goods|"
else:
# flash(" ")
goods=Goods.query.get(id)
#
simple_goods = goods
if goods:
simple_goods.timestamp = str(goods.timestamp)
# redis
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS']:
# redis ,5
Redis.set_data(r, key, simple_goods, current_app.config['EXPIRE_CACHED_PAGE_TO_REDIS'])
#
#
recommend_count = 4 if goods else 12
key = "data-cached:detail-recommend-%d" % recommend_count
list_recommend_goods = Redis.get_data(r, key)
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS'] and list_recommend_goods:
# flash(" ")
cached_redis_remark += "recommend|"
else:
list_recommend_goods = Goods.query.filter(Goods.coupon_expire >= today).filter_by(effective=True).limit(recommend_count).all()
# redis
if current_app.config['ENABLE_CACHED_PAGE_TO_REDIS']:
# redis ,5
Redis.set_data(r, key, list_recommend_goods, current_app.config['EXPIRE_CACHED_PAGE_TO_REDIS'])
return render_template("home/detail.html", goods=goods,list_goods=list_recommend_goods,cached_redis_remark=cached_redis_remark)