[英]In a flask project, what's an idiomatic way to define sql models after the app has been created?
I'm rather confused on where to define sql (flask-sqlalchemy) models in my flask app. 我对我的flask应用程序中的哪里定义sql(flask-sqlalchemy)模型感到困惑。 I have an app.py which creates the flask app (
app = Flask(__name__)
), and I have a models.py which instantiates SQLAlchemy and defines my models: 我有一个创建烧瓶应用程序的app.py(
app = Flask(__name__)
),还有一个models.py,它实例化SQLAlchemy并定义了我的模型:
from flask import current_app
db = SQLAlchemy(current_app)
class Habit(db.Model):
rowid = db.Column(db.Integer, primary_key=True)
However, the only way for this to work is if my app.py imports it after the app has been created, which goes against the python idiom of putting all imports at the top of the file. 但是,唯一可行的方法是如果我的app.py在创建应用程序后将其导入,这与将所有导入项放在文件顶部的python习惯相反。 However, this is what many example apps that I've seen do ( Ex. 1 ) ( Ex. 2 ).
但是,这就是我见过的许多示例应用程序( 示例1 )( 示例2 )所做的事情。
There's got to be a better way to define your models, but it feels like a catch 22. The models subclass db.Model, db is instantiated (using flask-sqlalchemy) using the flask app, and the flask app must import the models (or else that code won't run). 必须有一种更好的方法来定义模型,但是感觉就像是一个陷阱。22。使用flask应用程序实例化了模型子类db.Model,db(使用flask-sqlalchemy),并且flask应用程序必须导入模型(否则该代码将无法运行)。 I could create a new file that first imports the app and then the db, but idiomatically, it seems like the file that instantiates the Flask app tends to be the entry point for the application.
我可以创建一个新文件,该文件先导入应用程序,然后再导入数据库,但是习惯上来说,实例化Flask应用程序的文件似乎是该应用程序的入口点。
Any advice? 有什么建议吗? Thanks!
谢谢!
You can use init_app
method of Flask extensions to bound them to your Flask application after instantiating. 实例化后,可以使用Flask扩展的
init_app
方法将其绑定到Flask应用程序。 For example, your models.py module: 例如,您的models.py模块:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Habit(db.Model):
rowid = db.Column(db.Integer, primary_key=True)
And your launch file (app.py): 和您的启动文件(app.py):
from flask import Flask
from models import db
app = Flask()
db.init_app(app)
app.run()
It helps you to build modular applications with logic separated in different files. 它可以帮助您构建逻辑分离在不同文件中的模块化应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.