Skip to content

Instantly share code, notes, and snippets.

@sudodo
Created October 15, 2023 01:22
Show Gist options
  • Save sudodo/fbf8dba7141cb8f2c2caea34b6a330ca to your computer and use it in GitHub Desktop.
Save sudodo/fbf8dba7141cb8f2c2caea34b6a330ca to your computer and use it in GitHub Desktop.
Create DB tables in Flask app (resolving circular import issue)

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:

database.py

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

app.py

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()

models.py

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment