Skip to content Skip to sidebar Skip to footer

How To Avoid Circular Imports In A Flask App With Flask Sqlalchemy Models?

I'm getting into Flask and building out an app that uses Flask SQLAlchemy. I've created a basic API that works when all the code is in a single file, but would like to better organ

Solution 1:

Instead of having User import app and app import user, bring them together in init.

app/app.py

from flask importFlaskfrom flask_sqlalchemy importSQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

app/models/user.py

from app.app import db
classUser:
    pass#access db the way you want

app/views.py

from app.app import app,db
@app.route("/")defhome():
    return"Hello World"# use db as you want

app/__init__.py

from app import app
from app.models.userimportUserfrom app import views

This is the leanest fix to the problem. However, I would recommend using Application Factories

Solution 2:

I think the best way is reorganize the structure of your project. Try to move the view functions to a separate package or module. You can follow the exploreflask to organize your project. Or you can check my common project structure of Flask project.

Post a Comment for "How To Avoid Circular Imports In A Flask App With Flask Sqlalchemy Models?"