flask-session
一、flask-session使用
作用:将默认保存的签名cookie中的值 保存到 redis/memcached/file/Mongodb/SQLAlchemy
安装:pip3 install flask-session
from flask import Flask, session
from flask_session import RedisSessionInterface
import redis
app = Flask(__name__)
conn = redis.Redis(host='127.0.0.1', port=6379)
# app.session_interface
app.secret_key = 'sdfdsfds'
app.session_interface = RedisSessionInterface(conn, key_prefix='randy', use_signer=True, permanent=False)
@app.route('/')
def hello_world():
session['name'] = 'randy'
return 'Hello World!'
@app.route("/index")
def index():
print(session['name'])
return "ok"
if __name__ == '__main__':
app.run()
参数
- conn:连接数据库
- key_prefix='randy:前缀
- 'use_signer=True:默认为Flase, 则不需设置secret_key
- permanent=False: 关闭浏览器删除cookies,默认为true,不删除
二、flask-session封装
# 封装配置
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = Redis(host='127.0.0.1', port='6379')
Session(app)
from flask import Flask, session
from redis import Redis
from flask_session import Session
app = Flask(__name__)
app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = Redis(host='127.0.0.1', port='6379')
Session(app)
@app.route('/')
def hello_world():
session['name'] = 'randy'
return 'Hello World!'
@app.route("/index")
def index():
print(session['name'])
return "ok"
if __name__ == '__main__':
app.run()
三、总结
-
本身都是修改了app.session_interface的类
-
问题:设置cookie时,如何设定关闭浏览器则cookie失效。
from flask import Response Response.set_cookie('k','v',exipre=None)#这样设置即可 #在session中设置 app.session_interface=RedisSessionInterface(conn,key_prefix='randy',permanent=False) #一般不用,我们一般都设置超时时间,多长时间后失效
问题:cookie默认超时时间是多少?如何设置超时时间
#源码expires = self.get_expiration_time(app, session) 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),#这个配置文件控制