【问题标题】:Flask with SQLAlchemy working outside of application context带有 SQLAlchemy 的烧瓶在应用程序上下文之外工作
【发布时间】:2021-08-01 19:41:25
【问题描述】:

我有一个 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)

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

【问题讨论】:

    标签: flask sqlalchemy


    【解决方案1】:

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

    您必须做的是在请求开始后创建该引擎,这会稍微减慢路线。 @app.before_request 装饰器可能会在这里为您提供帮助:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2018-12-17
      相关资源
      最近更新 更多