通过引入第三方模块flask-session来将session信息保存到数据库中
flask-session的简单应用
from flask_session import Session,RedisSessionInterface from flask import Flask,session import redis from redis import Redis app = Flask(__name__)
# 第一种连接数据库方法 conn=redis.Redis(host='127.0.0.1',port=6379) app.session_interface=RedisSessionInterface(conn,key_prefix='flask_')
# 第二种方法 # app.config['SESSION_TYPE'] = 'redis' # app.config['SESSION_REDIS'] = Redis(host='127.0.0.1',port='6379') Session(app) @app.route('/') def enter(): session['name'] = 'zjh' return 'hello' @app.route('/get_name') def get_name(): res = session.get('name') print(res) return 'get_name' if __name__ == '__main__': app.run()