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-Migratepip install Flask-MigrateSetup
from flask_migrate import Migrate
migrate = Migrate(app, db)from flask_migrate import Migrate
migrate = Migrate(app, db)Typical workflow
- Initialize migrations folder:
flask db initflask db init- Create a migration script:
flask db migrate -m "create users table"flask db migrate -m "create users table"- Apply it:
flask db upgradeflask db upgradeKey idea
migratemigrategenerates migration scripts from model diffsupgradeupgradeapplies 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 coffeeWas this page helpful?
Let us know how we did
