I'm rather confused on where to define sql (flask-sqlalchemy) models in my flask app. 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:
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. However, this is what many example apps that I've seen do (Ex. 1) (Ex. 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). 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.
Any advice? Thanks!