Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. It simplifies the process of managing changes to your database schema over time, enabling you to apply migrations consistently and efficiently. In this article, we present three practical examples of using Flask-Migrate for database migrations.
Context: You are starting a new Flask application and need to set up your initial database schema.
To begin, you’ll want to create your database models and then generate your initial migration script with Flask-Migrate. This ensures your database matches the models you’ve defined.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
with app.app_context():
db.create_all()
# Generate the migration script
!flask db init
!flask db migrate -m "Initial migration"
!flask db upgrade
Notes:
db init
command initializes a migrations directory. The db migrate
command creates a new migration script, and db upgrade
applies the migration to the database.Context: You need to modify your existing User
model to include a new column for user profiles.
When you want to add new attributes to your database model, you need to create another migration to reflect these changes in your database.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
bio = db.Column(db.String(250), nullable=True) # New column for user bio
# After modifying the User model, run the following commands:
!flask db migrate -m "Add bio column to User"
!flask db upgrade
Notes:
flask db history
.Context: You realize that the bio
column in the User
model should be renamed to profile_description
for clarity.
Renaming columns is a common scenario in database migrations, and Flask-Migrate makes it straightforward to handle such changes.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
profile_description = db.Column(db.String(250), nullable=True) # Renamed column
# After modifying the User model, run the following commands:
!flask db migrate -m "Rename bio to profile_description"
!flask db upgrade
Notes:
By following these examples of using Flask-Migrate for database migrations, you can effectively manage and evolve your database schema alongside your application development.