Flask migrations with alembic without flask-migrate

The starting point for this setup was, that I wanted to be able to automigrate and to be able to move my models in a folder. And since flask-migrate is using a manager I opted out of that and used plain alembic with flask-sqlalchemy.

So, this is my Flask setup:

app.py
alembic.ini
models/
      shared_model.py
      ... the models ...
alembic/
      env.py
      ... versions/ and rest of alembic ...

So where is the magic happening?
Actually (spoilers!) there is no magic. Maybe I’m just a little daft, for not getting this right sooner. So here is what I do
In my shared_model.py I put my db declaration like this


from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

and the rest of the code I like to use in all models.

In my app.py I initialize my app via function


from flask import Flask
app = Flask(__name__)

def start_app():
      ... configuration magic ...
      db.init_app(app)
      return app

if __name__ == "__main__":
      app = start_app()
      app.run()

Finally the adjustments in alembic/env.py somewhere underneath the MetaData


from start import start_app
app = start_app()
from models.shared_model import db
db.init_app(app)
config.set_main_option("sqlalchemy.url", app.config["SQLALCHEMY_DATABASE_URI"])
target_metadata = db.metadata

An that’s it. Blueprints, autogenerate and all the fancies 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s