1、Flask模块中session与Flask-session组件中session的继承关系:
Flask模块sessions.py:
class SessionInterface(object): def open_session(self, app, request): raise NotImplementedError() def save_session(self, app, session, response): raise NotImplementedError() class SecureCookieSessionInterface(SessionInterface): def open_session(self, app, request): pass def save_session(self, app, session, response): pass
flask-session组件sessions.py:
class SessionInterface(FlaskSessionInterface): pass class NullSessionInterface(SessionInterface): pass class RedisSessionInterface(SessionInterface): pass class MemcachedSessionInterface(SessionInterface): pass class FileSystemSessionInterface(SessionInterface): pass class MongoDBSessionInterface(SessionInterface): pass class SqlAlchemySessionInterface(SessionInterface): pass
2、Flask-session在Flask项目中的使用
2.1、从Flask-session导入Session
flask_session import Session
2.2、配置参数
app.config['SESSION_TYPE'] = 'redis' # app.config['SESSION_TYPE'] = 'filesystem' app.config['SESSION_REDIS'] = redis.Redis(host='140.143.227.206',port=6379,password='1234')
2.3、实例化Session
Session(app)
实例化Session,根据配置的SESSION_TYPE类型实例化不同类型的SessionInterface,并将结果赋值给app.session_interface。
Session类源码:
class Session(object): """This class is used to add Server-side Session to one or more Flask applications. There are two usage modes. One is initialize the instance with a very specific Flask application:: app = Flask(__name__) Session(app) The second possibility is to create the object once and configure the application later:: sess = Session() def create_app(): app = Flask(__name__) sess.init_app(app) return app By default Flask-Session will use :class:`NullSessionInterface`, you really should configurate your app to use a different SessionInterface. .. note:: You can not use ``Session`` instance directly, what ``Session`` does is just change the :attr:`~flask.Flask.session_interface` attribute on your Flask applications. """ def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): """This is used to set up session for your app object. :param app: the Flask app object with proper configuration. """ app.session_interface = self._get_interface(app) def _get_interface(self, app): config = app.config.copy() # 如果SESSION_TYPE为空,设置SESSION_TYPE为空 config.setdefault('SESSION_TYPE', 'null') # 如果SESSION_PERMANENT为空,设置为永久的 config.setdefault('SESSION_PERMANENT', True) config.setdefault('SESSION_USE_SIGNER', False) # 如果SESSION_KEY_PREFIX为空,设置为key的前缀为session: config.setdefault('SESSION_KEY_PREFIX', 'session:') # 如果SESSION_REDIS为空,设置redis的连接为None config.setdefault('SESSION_REDIS', None) # 如果SESSION_MEMCACHED为空,设置memcached的连接为None config.setdefault('SESSION_MEMCACHED', None) # 如果SESSION_FILE_DIR为空,设置session的存储目录为当前目录flask_session文件夹 config.setdefault('SESSION_FILE_DIR', os.path.join(os.getcwd(), 'flask_session')) # 如果SESSION_FILE_THRESHOLD为空,设置文件阈值为500 config.setdefault('SESSION_FILE_THRESHOLD', 500) # 如果SESSION_FILE_MODE为空,设置文件模式为384 config.setdefault('SESSION_FILE_MODE', 384) # 如果SESSION_MONGODB为空,设置mongodb的连接为None config.setdefault('SESSION_MONGODB', None) # 如果SESSION_MONGODB_DB为空,设置存储session的mongodb数据库为flask_session config.setdefault('SESSION_MONGODB_DB', 'flask_session') # 如果SESSION_MONGODB_COLLECT为空,设置存储session的mongodb的表名为sessions config.setdefault('SESSION_MONGODB_COLLECT', 'sessions') # 如果SESSION_SQLALCHEMY为空,设置SQLALCHEMY的连接为None config.setdefault('SESSION_SQLALCHEMY', None) # 如果SESSION_SQLALCHEMY_TABLE为空,设置SQLALCHEMY的表名为sessions config.setdefault('SESSION_SQLALCHEMY_TABLE', 'sessions') # session存储在redis if config['SESSION_TYPE'] == 'redis': # 实例化redis session接口 session_interface = RedisSessionInterface( config['SESSION_REDIS'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) # session存储在memcached elif config['SESSION_TYPE'] == 'memcached': session_interface = MemcachedSessionInterface( config['SESSION_MEMCACHED'], config['SESSION_KEY_PREFIX'], config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) # session存储在filesystem 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']) # session存储在mongodb 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']) # session存储在sqlalchemy 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']) # 不使用session else: session_interface = NullSessionInterface() return session_interface
2.4、Flask-session支持的session存储方式
存储方式 | session操作接口类 |
redis | RedisSessionInterface |
memcached | MemcachedSessionInterface |
filesystem | FileSystemSessionInterface |
mongodb | MongoDBSessionInterface |
sqlalchemy | SqlAlchemySessionInterface |