DEV Community

Salima Dergoul
Salima Dergoul

Posted on

Avoiding Circular Imports in Flask Projects

For avoiding the circular import in flask projects, we do the import at the bottom of our code.
For example, in the routes.py file I have two imports app and db like so:
from app import app, db

  • If you import routes at the top of app.py, Python will try to load routes.py before app and db are fully defined.
    - That creates a circular dependency:

  • app.py imports routes

  • routes.py imports app

  • Neither file finishes loading → error or undefined objects.

  • By placing import routes at the bottom, you ensure:

  • app, db, jwt, and migrate are initialized first.

  • Then routes.py can safely attach endpoints to app.

in the app.py file:

`from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_migrate import Migrate

Create the Flask application instance

app = Flask(name)

Load configuration settings (e.g., DB URI, JWT secret key) from config.py

app.config.from_object("config.Config")

Initialize SQLAlchemy ORM with the app

db = SQLAlchemy(app)

Initialize JWT manager for authentication

jwt = JWTManager(app)

Initialize Flask-Migrate for database migrations

migrate = Migrate(app, db)

Custom CLI command: create all database tables

@app.cli.command("db_create")
def db_create():
db.create_all()
print("db created!.")

Custom CLI command: drop all database tables

@app.cli.command("db_drop")
def db_drop():
db.drop_all()
print("db dropped!.")

Import routes AFTER app, db, jwt, migrate are defined

This avoids circular imports (routes.py needs app and db)

import routes`

in the routes.py file:

`from flask import jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import Post

def register_routes(app):
@app.route("/v1/post", methods=["POST"])
@jwt_required()
def add_post():
user_id = int(get_jwt_identity())
data = request.get_json()
post = Post(title=data["title"], body=data["body"], author_id=user_id)
db.session.add(post)
db.session.commit()
return jsonify(message="Post created successfully"), 201`

Top comments (0)