Flask 第三方组件 flask-session
Flask-Session下载与介绍
- 下载:
pip install Flask-Session
- 介绍:
Flash 中的session是保存在浏览器中的cookie中;
flask-session 是将session序列化后保存在数据库中;
基本用法
- 示例:
from flask import Flask, session from flask_session import Session from redis import Redis app = Flask(__name__) app.config.from_object(DebugSetting) # 选择数据库的类型 app.config["SESSION_TYPE"] = "redis" # 连接redis app.config["SESSION_REDIS"] = Redis() Session(app) @app.route("/home") def home(): session["token"] = "asd541sdf4ag345a5a68d7fa6d3f" return "HOME" @app.route("/home2") def home2(): print(session.get("token")) return session.get("token") if __name__ == '__main__': app.run()
- 使用:
- 配置两个变量
app.config["SESSION_TYPE"] = "redis"
app.config["SESSION_REDIS"] = Redis()
- 导入flask-session, 并且实例化Session,将flask的实例化对象传入即可;
from flask_session import Session
app = Flask(__name__)
Session(app)
配置文件
- 设置配置源码以及解析:
def _get_interface(self, app): config = app.config.copy() config.setdefault('SESSION_TYPE', 'null') config.setdefault('SESSION_PERMANENT', True) config.setdefault('SESSION_USE_SIGNER', False) config.setdefault('SESSION_KEY_PREFIX', 'session:') config.setdefault('SESSION_REDIS', None) config.setdefault('SESSION_MEMCACHED', None) config.setdefault('SESSION_FILE_DIR', os.path.join(os.getcwd(), 'flask_session')) config.setdefault('SESSION_FILE_THRESHOLD', 500) config.setdefault('SESSION_FILE_MODE', 384) config.setdefault('SESSION_MONGODB', None) config.setdefault('SESSION_MONGODB_DB', 'flask_session') config.setdefault('SESSION_MONGODB_COLLECT', 'sessions') config.setdefault('SESSION_SQLALCHEMY', None) config.setdefault('SESSION_SQLALCHEMY_TABLE', 'sessions') if config['SESSION_TYPE'] == 'redis': session_interface = RedisSessionInterface( config['SESSION_REDIS'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'memcached': session_interface = MemcachedSessionInterface( config['SESSION_MEMCACHED'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'filesystem': session_interface = FileSystemSessionInterface( config['SESSION_FILE_DIR'], config['SESSION_FILE_THRESHOLD'], config['SESSION_FILE_MODE'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'mongodb': session_interface = MongoDBSessionInterface( config['SESSION_MONGODB'], config['SESSION_MONGODB_DB'], config['SESSION_MONGODB_COLLECT'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) elif config['SESSION_TYPE'] == 'sqlalchemy': session_interface = SqlAlchemySessionInterface( app, config['SESSION_SQLALCHEMY'], config['SESSION_SQLALCHEMY_TABLE'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) else: session_interface = NullSessionInterface() return session_interface
源码剖析