flask 引入redis 替换原生session存储session(flask-session)
环境:
python 3.7.4
win 10 环境
redis 服务
模块依赖:
flask
flask-session
redis
工程目录:
flask 引入redis 替换原生session存储session(flask-session)
在配置文件中加入redis连接配置以及flask-session 替换为 redis方式
import uuid, os from redis import Redis class BasicConfig(object): # SECRET_KEY = os.urandom(24) SECRET_KEY = str(uuid.uuid4()) class DevConfig(BasicConfig): DEBUG = True # Mysql 配置 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1/anec' SQLALCHEMY_TRACK_MODIFICATIONS = 'False' SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 15 # redis 与 flask-session 配置 SESSION_TYPE = 'redis' # session存储格式为redis SESSION_REDIS = Redis(host='192.168.0.118', port=6379) SESSION_USE_SIGNER = True # 是否强制加盐,混淆session SESSION_PERMANENT = False # sessons是否长期有效,false,则关闭浏览器,session失效 PERMANENT_SESSION_LIFETIME = 3600 # session长期有效,则设定session生命周期,整数秒,默认大概不到3小时。
在views 中使用 session
from App.RedisSession import redissession from flask import session, request @redissession.route('/') def default(): return session.get('key', 'not set') @redissession.route('/test/') def test(): session['key'] = 'test' return 'ok' @redissession.route('/set/') def set(): # 从请求头中获取 新的Key值 arg = request.args.get('key') print(arg) session['key'] = arg return 'ok' @redissession.route('/get/') def get(): return session.get('key', 'not set') @redissession.route('/pop/') def pop(): session.pop('key') return session.get('key', 'not set') @redissession.route('/clear/') def clear(): session.clear() return session.get('key', 'not set')
既要脚踏实地,也需仰望天空