【问题标题】:Flask and SqlAlchemy sessionFlask 和 SqlAlchemy 会话
【发布时间】:2018-02-08 10:06:38
【问题描述】:

我一直在构建一个烧瓶应用程序并使用 flask-sqlalchemy 和 flask-migrate。 最近我决定用普通的 sqlalchemy 和 alembic 替换扩展,我开始思考存储 db session 对象 (sqla) 的最佳位置是什么。

现在我有以下内容:

Base = declarative_base()


def init_db_session(app, expire_on_commit=True):
    """
    Initialize the database
    """
    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
    db_session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, expire_on_commit=expire_on_commit, bind=engine)
    )

    Base.query = db_session.query_property()

    return db_session

def init_app(app):
    """
    Flask app initialization and bootstrap
    """
    init_logging(app)
    app.celery = init_celery(app)
    app.db_session = init_db_session(app)

但是鉴于网上的一些文档和示例,我想知道使用 flask global g 是否更好

它们都属于同一个上下文,我在文档和代码中读到了这一点,但我仍然无法理解实际差异以及将其放在 current_app中的潜在缺点> 与 g

相比

【问题讨论】:

    标签: python flask sqlalchemy


    【解决方案1】:

    flask documentation 建议在模块范围内声明会话。这也是我在自己的代码中使用它的方式。

    Base = declarative_base()
    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
    db_session = scoped_session(
        sessionmaker(
            autocommit=False,
            autoflush=False,
            expire_on_commit=expire_on_commit,
            bind=engine
        )
    )
    
    Base.query = db_session.query_property()
    
    
    def init_db():
    """ not much to do here if migrations are handled else where. """
        pass
    
    
    def init_app(app):
        """
        Flask app initialization and bootstrap
        """
        init_logging(app)
        app.celery = init_celery(app)
        app.db_session = init_db_session(app)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2016-02-24
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多