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 import Flask
from flask_sqlalchemy import SQLAlchemy

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

app/models/user.py

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

app/views.py

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

app/__init__.py

from app import app
from app.models.user import User
from 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?"