我有一个 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)
但它不起作用。我该如何解决这个问题?