0
0
FlaskHow-ToBeginner · 4 min read

How to Run Database Migration in Flask with Flask-Migrate

To run migrations in Flask, use the Flask-Migrate extension which integrates Alembic for database schema changes. Initialize migrations with flask db init, create migration scripts with flask db migrate, and apply them using flask db upgrade.
📐

Syntax

Flask-Migrate commands are run in the terminal to manage database migrations:

  • flask db init: Creates the migration folder to track changes.
  • flask db migrate -m "message": Generates a new migration script based on model changes.
  • flask db upgrade: Applies the migration to the database.
bash
flask db init
flask db migrate -m "Initial migration"
flask db upgrade
💻

Example

This example shows how to set up Flask-Migrate and run a migration after adding a new model field.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'

# Initialize database and migration

db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Define a simple model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)

# After adding a new field, e.g., email
# class User(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     username = db.Column(db.String(64), unique=True, nullable=False)
#     email = db.Column(db.String(120), unique=True, nullable=True)

if __name__ == '__main__':
    app.run()
⚠️

Common Pitfalls

1. Forgetting to initialize migrations: You must run flask db init once before other commands.

2. Not importing models before migration: Migration scripts detect changes by importing your models, so ensure models are imported in your app.

3. Running migrations without activating the Flask app context: Set FLASK_APP environment variable or use flask --app yourapp.

bash
### Wrong: Running migrate without init
flask db migrate -m "Add field"

### Right: Initialize first
flask db init
flask db migrate -m "Add field"
flask db upgrade
📊

Quick Reference

CommandDescription
flask db initCreate migration repository folder
flask db migrate -m "msg"Generate migration script from model changes
flask db upgradeApply migrations to the database
flask db downgradeRevert last migration
flask db currentShow current migration version

Key Takeaways

Use Flask-Migrate commands to manage database schema changes safely.
Always run 'flask db init' once before creating migrations.
Import your models so migration scripts detect changes correctly.
Run 'flask db migrate' to generate migration scripts after model updates.
Apply changes with 'flask db upgrade' to update the database.