Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask circular dependency

I am developing a Flask application. It is still relatively small. I had only one app.py file, but because I needed to do database migrations, I divided it into 3 using this guide:

https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/

However, I now can't run my application as there is a circular dependency between app and models.

app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template, request, redirect, url_for
import os

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.debug = True

db = SQLAlchemy(app)

from models import User

... routes ...    

if __name__ == "__main__":
  app.run()

models.py:

from app import db
class User(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(80), unique=True)
  email = db.Column(db.String(120), unique=True)

  def __init__(self, username, email):
    self.username = username
    self.email = email

  def __repr__(self):
    return self.username

manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db

migrate = Migrate(app, db)
manager = Manager(app)

manager.add_command('db', MigrateCommand)

if __name__ == "__main__":
  manager.run()

They are all in the same directory. When I try to run python app.py to start the server, I receive an error which definitely shows a circular dependency (which is pretty obvious). Did I make any mistakes when following the guide or is the guide wrong? How can I refactor this to be correct?

Thanks a lot.

EDIT: Traceback

Traceback (most recent call last):
  File "app.py", line 14, in <module>
    from models import User
  File "/../models.py", line 1, in <module>
    from app import db
  File "/../app.py", line 14, in <module>
    from models import User
ImportError: cannot import name User
like image 320
pavlos163 Avatar asked Aug 28 '26 21:08

pavlos163


1 Answers

I propose the following structure:

# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...


# app/app.py
from app.extensions import db

def create_app(config_object=ProdConfig):
    app = Flask(__name__.split('.')[0])
    app.config.from_object(config_object)
    register_extensions(app)
    ...

def register_extensions(app):
    db.init_app(app)
    ...

# manage.py
from yourapp.app import create_app
app = create_app()
app.debug = True
...

In this case, database, app, and your models are all in separate modules and there are no conflicting or circular imports.

like image 62
leovp Avatar answered Aug 31 '26 10:08

leovp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!