I was trying to package my code as it was getting kind of complex for me to keep in one file and i encountered an import error when i tried to run the file that says circular import error, how do i solve this error? I have been analyzing the code and i cannot seem to be able to figure out what might be wrong.
run.py
JavaScript
x
5
1
from market import app
2
3
if __name__ == "__main__":
4
app.run(debug=True)
5
init.py
JavaScript
1
8
1
from flask import Flask, render_template
2
from flask_sqlalchemy import SQLAlchemy
3
from market import routes
4
5
app = Flask(__name__)
6
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///market.db"
7
db = SQLAlchemy(app)
8
routes.py
JavaScript
1
16
16
1
from market import app
2
from flask import render_template
3
from market.models import Item
4
5
6
@app.route("/")
7
@app.route("/home")
8
def home():
9
return render_template("index.html")
10
11
12
@app.route("/market")
13
def market():
14
items = Item.query.all()
15
return render_template("market.html", items=items)
16
models.py
JavaScript
1
13
13
1
from market import db
2
3
4
class Item(db.Model):
5
id = db.Column(db.Integer(), primary_key=True)
6
name = db.Column(db.String(length=30), nullable=False, unique=True)
7
price = db.Column(db.Integer(), nullable=False)
8
barcode = db.Column(db.String(length=12), nullable=False, unique=True)
9
description = db.Column(db.String(length=1024), nullable=False, unique=True)
10
11
def __repr__(self):
12
return f"Item {self.name}"
13
Advertisement
Answer
Moving your routes import to the bottom of the file should help.
Just as you would do for example with blueprints in application factory. You import blueprints/views after you create app instance with app = Flask(__name__)
:
JavaScript
1
15
15
1
def create_app(config_filename):
2
app = Flask(__name__)
3
app.config.from_pyfile(config_filename)
4
5
from yourapplication.model import db
6
db.init_app(app)
7
8
9
from yourapplication.views.admin import admin
10
from yourapplication.views.frontend import frontend
11
app.register_blueprint(admin)
12
app.register_blueprint(frontend)
13
14
return app
15
Also check: Is a Python module import at the bottom ok?