How do I use flask-migrate to manage DB scheme changes?

Using Flask-Migrate to manage updates to your database is an excellent choice for handling schema changes over time. Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. Here’s how to set it up and use it:

Step 1: Install Flask-Migrate

If you haven’t already installed Flask-Migrate, you can do so via pip:

pip install Flask-Migrate

Step 2: Integrate Flask-Migrate into Your Flask Application

Modify your Flask application to include Flask-Migrate. Here’s an example:

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

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user1:password1@localhost/db1'
app.config['SQLALCHEMY_BINDS'] = {
    'db2': 'mysql://user2:password2@localhost/db2'
}

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

Step 3: Initialize the Migration Environment

Run the following command to initialize your migration environment. This will add a migrations folder to your project, which will store migration scripts.

flask db init

Step 4: Generating an Initial Migration

After you’ve defined your models you can create an initial migration:

flask db migrate -m "Initial migration."

This command will generate a migration script in the migrations/versions directory.

Step 5: Apply the Migration

To apply the migration to your database, run:

flask db upgrade

This will apply the changes defined in your migration script to the database.

Step 6: Making Changes to the Model

Whenever you make changes to your database models, you’ll need to generate a new migration script and apply it:

  1. Modify the Model: Make your changes to the model (e.g., adding new fields).
  2. Generate a New Migration: Run the migration command again:
   flask db migrate -m "Added new fields to Model"
  1. Apply the New Migration: Upgrade your database to apply the changes:
   flask db upgrade

Step 7: Rolling Back Changes

If you need to undo a migration, you can use:

flask db downgrade

This will revert the last migration applied.

Additional Notes

  • Always review the migration scripts generated by flask db migrate before applying them with flask db upgrade, especially in a production environment.
  • It’s a good practice to keep your migration scripts in version control.
  • Remember to configure your production database URI appropriately and ensure that your application has the necessary permissions to alter the database schema.
  • Use flask db --help to see other commands and options available with Flask-Migrate.