在研究了 Flask-Session/ init .py 代码后,我发现其下的 SqlAlchemySessionInterface 类__init__
包含一个 Flask-SQLAlchemy 模型
class Session(self.db.Model)
。为了创建这个表模型,在我创建模型的文件中,我SqlAlchemySessionInterface
从中导入flask_sessionstore
并放置行
SqlAlchemySessionInterface(myApp, sqlAlchemyDbObject, "table_name", "prefix_")
,然后运行 db.create_all()。
class SqlAlchemySessionInterface(SessionInterface):
"""Uses the Flask-SQLAlchemy from a flask app as a session backend.
.. versionadded:: 0.2
:param app: A Flask app instance.
:param db: A Flask-SQLAlchemy instance.
:param table: The table name you want to use.
:param key_prefix: A prefix that is added to all store keys.
:param use_signer: Whether to sign the session id cookie or not.
:param permanent: Whether to use permanent session or not.
"""
serializer = pickle
session_class = SqlAlchemySession
def __init__(self, app, db, table, key_prefix, use_signer=False,
permanent=True):
if db is None:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
self.db = db
self.key_prefix = key_prefix
self.use_signer = use_signer
self.permanent = permanent
class Session(self.db.Model):
__tablename__ = table
id = self.db.Column(self.db.Integer, primary_key=True)
session_id = self.db.Column(self.db.String(255), unique=True)
data = self.db.Column(self.db.LargeBinary)
expiry = self.db.Column(self.db.DateTime)
def __init__(self, session_id, data, expiry):
self.session_id = session_id
self.data = data
self.expiry = expiry
def __repr__(self):
return '<Session data %s>' % self.data
# self.db.create_all()
self.sql_session_model = Session
我肯定会在我的下一个项目中使用 Django。许多 Flask Extensions 的文档都不是很好。
编辑
更改(从 flask_session 导入SqlAlchemySessionInterface)为(从 flask_sessionstore 导入SqlAlchemySessionInterface)