When working with Flask, circular imports (like importing db
from app
in models.py
and User
from models
in app.py
) can sometimes cause problems. To address this, you might want to create a separate file, say database.py
, where you define and configure the SQLAlchemy instance, and then import db
from this new file wherever it’s needed.
Example with a separate database.py
file:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from flask import Flask
from flask_migrate import Migrate
import logging
from database import db # Importing db from database.py
from models import User # Ensure this line is present
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hestia-web.db'
db.init_app(app)
migrate = Migrate(app, db)
class UserTemp(db.Model):
id = db.Column(db.Integer, primary_key=True) # USER-ID
email = db.Column(db.String(120), unique=True, nullable=False)
with app.app_context():
logging.info('create_tables called')
db.create_all()
from database import db # Importing db from database.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True) # USER-ID
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
By organizing the code in this manner, you should avoid issues related to circular imports and ensure that all your models are known to SQLAlchemy when creating the database tables.