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
from market import app if __name__ == "__main__": app.run(debug=True)
init.py
from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy from market import routes app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///market.db" db = SQLAlchemy(app)
routes.py
from market import app from flask import render_template from market.models import Item @app.route("/") @app.route("/home") def home(): return render_template("index.html") @app.route("/market") def market(): items = Item.query.all() return render_template("market.html", items=items)
models.py
from market import db class Item(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(length=30), nullable=False, unique=True) price = db.Column(db.Integer(), nullable=False) barcode = db.Column(db.String(length=12), nullable=False, unique=True) description = db.Column(db.String(length=1024), nullable=False, unique=True) def __repr__(self): return f"Item {self.name}"
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__)
:
def create_app(config_filename): app = Flask(__name__) app.config.from_pyfile(config_filename) from yourapplication.model import db db.init_app(app) from yourapplication.views.admin import admin from yourapplication.views.frontend import frontend app.register_blueprint(admin) app.register_blueprint(frontend) return app
Also check: Is a Python module import at the bottom ok?