使用 Flask-sqlalchemy,无需 运行 应用程序即可将模型连接到数据库

with Flask-sqlalchemy, connect models to database without running app

我使用 this 问题的答案来修复设置 Flask-SQLAlchemy 时的循环导入。该解决方案之所以有效,是因为您不必从 application.py 文件导入 app 来获取数据库 URI - 它会在 运行 应用程序之前初始化连接。现在的问题是,我通常喜欢将我的 models 文件导入 python 解释器,这样我就可以测试模型(以及与数据库的连接)而实际上 运行 应用程序。但是使用此设置,仅导入 models 不会与 PostGres 建立连接。

有没有办法通过 Flask-SQLAlchemy 建立与 PostGres 的连接而无需实际初始化和 运行 应用程序?也许我可以直接向 db 提供我的数据库的 URI?

学习这段代码 https://github.com/mattupstate/overholt github 上有一个 link 解释设计。你的主要关注点应该是 flask-script 的使用。我认为你必须使用工厂模式,但如果你正在做任何非常严肃的事情,你无论如何都想这样做。

祝你好运

你好像在找这个github.com/mardix/active-alchemy

Active-Alchemy is a framework agnostic wrapper for SQLAlchemy that makes it really easy to use by implementing a simple active record like api, while it still uses the db.session underneath. Inspired by Flask-SQLAlchemy