带有 SQLAlchemy 的 Flask 在应用程序上下文之外工作

我有一个 flask 应用程序,我使用 SQLAlchemy(没有 flask 扩展,因为我需要创建我自己的基于类的 SQLAlchemy 等等)。

我的应用程序通过引擎连接到它的数据库,它工作正常,但现在我需要动态创建我的引擎并从 flask.g 获取 db_name

引擎在models.py中声明

models.py

engine = create_engine(f"postgresql://postgres:postgres@localhost:5434/{g['tenant']}",convert_unicode=True)

db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()

对于启动应用程序,我使用 wsgi.py:

from app import app


if __name__ == "__main__":

    app.run(port=5002)

当我输入 python wsgi.py 时,我收到一个错误。

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this,set up an application context with app.app_context().  See the
documentation for more information.

总的来说,我理解我使用的是上下文之外的引擎。问题是 - 我不知道如何将我的引擎变量传递给上下文。

我尝试创建应用功能:

def create_app():
    app = flask(__name__)

    with app.app_context():
        engine = create_engine(f"postgresql://postgres:postgres@localhost:5434/{g['tenant']}",convert_unicode=True)
    return app

我也试过 app.app_context().push(engine)

但它不起作用。我该如何解决这个问题?

solabc 回答:带有 SQLAlchemy 的 Flask 在应用程序上下文之外工作

问题在于,flask 对象 g 仅在当前正在flask 上进行请求时才存在。 (没有请求,就没有flask g,因为g是专门针对单个请求的全局)

您需要做的是在请求开始后创建该引擎,这会稍微减慢路由速度。 @app.before_request 装饰器可能会在这里帮助你:

$identifier

(“before_request”已经是“在请求期间”——它只是flask“在请求开始时”做的第一件事)

本文链接:https://www.f2er.com/763.html

大家都在问