【发布时间】: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