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.

Install

pip install Flask-Migrate
pip install Flask-Migrate

Setup

from flask_migrate import Migrate
 
migrate = Migrate(app, db)
from flask_migrate import Migrate
 
migrate = Migrate(app, db)

Typical workflow

  1. Initialize migrations folder:
flask db init
flask db init
  1. Create a migration script:
flask db migrate -m "create users table"
flask db migrate -m "create users table"
  1. Apply it:
flask db upgrade
flask db upgrade

Key idea

  • migratemigrate generates migration scripts from model diffs
  • upgradeupgrade applies them to the database

Best practices

  • review generated scripts before applying
  • commit migrations to git
  • run migrations in CI/staging before production

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did