Skip to content

Database Migrations (Flask-Migrate)

Migrations solve a dangerous problem:

  • your models change over time
  • your database schema must change too
  • you need a safe, repeatable way to apply those changes

Flask-Migrate wraps Alembic to manage migrations.

diagram why create_all is not migrations mermaid
create_all only creates tables that do not exist yet. It will never alter one that does, so the moment you add a column to a model that is already in the database, the two drift apart silently. Flask-Migrate records each change as a versioned script, so the database can be moved forward -- and back -- deliberately.
bash
pip install Flask-Migrate
python
from flask_migrate import Migrate
 
migrate = Migrate(app, db)
  1. Initialize migrations folder:
bash
flask db init
  1. Create a migration script:
bash
flask db migrate -m "create users table"
  1. Apply it:
bash
flask db upgrade
  • migrate generates migration scripts from model diffs
  • upgrade applies them to the database
  • review generated scripts before applying
  • commit migrations to git
  • run migrations in CI/staging before production

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading