简体   繁体   English

Flask 和 SqlAlchemy 会话

[英]Flask and SqlAlchemy session

I've been building a flask app and using flask-sqlalchemy and flask-migrate.我一直在构建一个烧瓶应用程序并使用烧瓶 sqlalchemy 和烧瓶迁移。 Lately I decided to replace the extension with plain sqlalchemy and alembic and I started to think what's the best place to store the db session object (sqla).最近我决定用普通的 sqlalchemy 和 alembic 替换扩展,我开始思考存储 db 会话对象 (sqla) 的最佳位置是什么。

Right now I have the following:现在我有以下几点:

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)

but given some docs and examples online I'm wondering if using flask global g is any better但给出了一些在线文档和示例,我想知道使用flask global g是否更好

They both belong to the same context, I read about that in the docs and in the code but still can't get my head around the practical differences and the potential drawbacks of having it in the current_app compared to g它们都属于同一上下文,我在文档和代码中阅读了相关内容,但仍然无法理解与g相比在current_app中使用它的实际差异和潜在缺点

The flask documentation has a recommendation to declare the session in the module scope. flask 文档建议在模块范围内声明会话。 This is also how I use it in my own code.这也是我在自己的代码中使用它的方式。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM