Flask circular dependency

2024/9/22 3:55:58

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 osapp = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Falseapp.debug = Truedb = 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 = usernameself.email = emaildef __repr__(self):return self.username

manage.py:

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, dbmigrate = 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 UserFile "/../models.py", line 1, in <module>from app import dbFile "/../app.py", line 14, in <module>from models import User
ImportError: cannot import name User
Answer

I propose the following structure:

# app/extensions.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
...# app/app.py
from app.extensions import dbdef 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.

https://en.xdnf.cn/q/71985.html

Related Q&A

How to create tox.ini variables

Is there a way to set arbitrary variables within tox.ini?An example would be a project name that might be used in a variety of ways. With a rather complex tox.ini, I find myself copy and pasting all …

How to apply json_normalize on entire pandas column

I have a dataframe with LISTS(with dicts) as column values . My intention is to normalize entire column(all rows). I found way to normalize a single row . However, Im unable to apply the same function …

Configure Vs code version 2.0.0 Build Task for python

I need help in configuring my Vs code to run scripts in python using Cntrl Shift B, I was working fine until Vs code upgraded to version 2.0.0 now it wants me to configure the Build. And I am clueless…

Generate N-Grams from strings with pandas

I have a DataFrame df like this: Pattern String 101 hi, how are you? 104 what are you doing? 108 Python is good to learn.I want to crea…

Merge dataframes on multiple columns with fuzzy match in Python

I have two example dataframes as follows:df1 = pd.DataFrame({Name: {0: John, 1: Bob, 2: Shiela}, Degree: {0: Masters, 1: Graduate, 2: Graduate}, Age: {0: 27, 1: 23, 2: 21}}) df2 = pd.DataFrame({Name: {…

Prevent Celery Beat from running the same task

I have a scheduled celery running tasks every 30 seconds. I have one that runs as task daily, and another one that runs weekly on a user specified time and day of the week. It checks for the "star…

Tastypie with application/x-www-form-urlencoded

Im having a bit of difficulty figuring out what my next steps should be. I am using tastypie to create an API for my web application. From another application, specifically ifbyphone.com, I am receivin…

Check for areas that are too thin in an image

I am trying to validate black and white images (more of a clipart images - not photos) for an engraving machine. One of the major things I need to take into consideration is the size of areas (or width…

Sort Python Dictionary by Absolute Value of Values

Trying to build off of the advice on sorting a Python dictionary here, how would I go about printing a Python dictionary in sorted order based on the absolute value of the values?I have tried:sorted(m…

impyla hangs when connecting to HiveServer2

Im writing some ETL flows in Python that, for part of the process, use Hive. Clouderas impyla client, according to the documentation, works with both Impala and Hive.In my experience, the client worked…