How to wire up migrations in Flask with declarative base?


I’m using the declarative Base in flask_sqlalchemy. In my file I have the following:

from sqlalchemy import create_engine
# from sqlalchemy.orm import scoped_session, sessionmaker
# from sqlalchemy.ext.declarative import declarative_base
# from flask_sqlalchemy import SQLAlchemy

# engine = create_engine("postgresql://postgres:@localhost/video_comparisons", convert_unicode=True)
# db_session = scoped_session(sessionmaker(autocommit=False,
#                                          autoflush=False,
#                                          bind=engine))
# Base = declarative_base()
# Base.query = db_session.query_property()

# Session = sessionmaker(bind = engine)

# db = SQLAlchemy()

# def init_db():
#     # import all modules here that might define models so that
#     # they will be registered properly on the metadata.  Otherwise
#     # you will have to import them first before calling init_db()
#     import yourapplication.models
#     Base.metadata.create_all(bind=engine)

Now, each of my models imports the Base object from This avoids circular imports.

Next, I’m trying to wire up the Flask migration module, which should work like this:

db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)

As you can see, I need to pass db into the Migrate constructor. But I don’t have a db object, because I’m using the declarative Base, not creating it with db = SQLAlchemy(app).

What’s the best way to do this? In the docs, I can’t see how to connect the Migrate object to the database with this syntax.



You have to import the db object from 🙂

Answered By – Louise

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published