flask-session

flask-session

第三方 flask-session,可以把session的内容保存在服务端

安装并使用

pip3 install flask-session

方式一

from flask import Flask,session
from flask_session.redis import RedisSessionInterface
import redis

app = Flask(__name__)
app.secret_key = 'adsfasdfads'
conn = redis.Redis(host='127.0.0.1', port=6379)
# 1 client:redis链接对象
# 2 key_prefix:放到redis中得前缀
# 3 use_signer:是否使用secret_key 加密
# 4 permanent:关闭浏览器,cookie是否失效
# 5 sid_length:生成session_key的长度
app.session_interface = RedisSessionInterface(app, client=conn, key_prefix='session', use_signer=True, permanent=True,sid_length=32)


@app.route('/index')
def index():
    session['name'] = 'xxx'
    return 'hello'


if __name__ == '__main__':
    app.run()

方式二

from flask import Flask, session
from redis import Redis
from flask_session import Session

app = Flask(__name__)
app.debug = True

app.config['SESSION_TYPE'] = 'redis'
app.config['SECRET_KEY'] = 'ddd7d55ee7dad'
app.config['SESSION_REDIS'] = Redis(host='127.0.0.1', port='6379')
app.config['SESSION_KEY_PREFIX'] = 'qcc'
Session(app)


@app.get('/index')
def index():
    session['name'] = 'qcc'
    return 'ok'


if __name__ == '__main__':
    app.run()
posted @ 2024-06-24 08:57  蓝幻ﹺ  阅读(3)  评论(0编辑  收藏  举报