2017-09-04 68 views
0

我正試圖在我的python應用程序中實現Flask-Session。我在文檔中讀到,推薦使用SqlAlchemySessionInterface之類的另一個界面,而不是默認的NullSessionInterface,當SESSION_TYPE配置密鑰沒有提供任何內容時使用。類會話下我是否需要創建一個會話表來使用Flask-Session SqlAlchemySessionInterface

從flask_session/初始化 .py文件讀取

默認瓶會話將使用:類:NullSessionInterface,你 真的應該configurate您的應用程序使用不同的SessionInterface。

SESSION_TYPE配置項設置爲"sqlalchemy"後,我得到一個錯誤

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "sessions" does not exist 

這表明瓶會話正在使用一個表在我的數據庫模型命名爲「會議」,但我不能在Flask-Session文檔中的任何地方找到它應該創建的表以及它應該具有的字段。

任何人都可以提出一個解決方案嗎?

回答

0

研究燒瓶會議後/ 初始化根據其__init__包含瓶,SQLAlchemy的模型 class Session(self.db.Model)的.py代碼,我發現,類SqlAlchemySessionInterface。 要創建此表模型,在創建我的模型的文件中,我從flask_session導入了SqlAlchemySessionInterface,並將行 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擴展的文檔都不是很好。

相關問題