0
votes

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!

1
Well, I never found better architecture than do the imports in the middle of the file. It's not pep8, but it seems to be the flask way.erhesto

1 Answers

0
votes

You can use init_app method of Flask extensions to bound them to your Flask application after instantiating. For example, your models.py module:

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):

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.