In this tutorial, we will delve into the world of database migration management using Flask-Migrate, a Flask extension that handles SQLAlchemy database migrations. The goal of this tutorial is to guide you through the process of managing database schema changes over time.
By the end of this tutorial, you will learn:
- How to set up Flask-Migrate
- How to handle database schema changes
- How to apply and rollback migrations
Prerequisites:
- Basic knowledge of Python
- Familiarity with Flask and SQLAlchemy
Flask-Migrate is a wrapper around Alembic, a database migration tool for SQLAlchemy. To get started, we install Flask-Migrate using pip:
pip install flask-migrate
After installation, we need to initialize Flask-Migrate and link it to our SQLAlchemy database:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
In the above code, we first import the necessary modules. Then, we create an instance of Flask, SQLAlchemy, and Migrate.
To create a migration, we use the flask db migrate
command. This command autogenerates a migration script based on the changes detected in the database schema:
flask db migrate -m "Your message"
The -m
flag allows you to add a message to your migration.
To apply the migrations, we use the flask db upgrade
command:
flask db upgrade
To undo migrations, we use the flask db downgrade
command:
flask db downgrade
Let's assume we have a User model and we want to add a new column, email
:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
Now we add an email field:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
email = db.Column(db.String(120), unique=True)
Next, we create and apply the migration:
# Terminal
flask db migrate -m "Added email field"
flask db upgrade
In this tutorial, we learned how to set up Flask-Migrate, create, apply, and rollback database migrations.
For further learning, consider exploring how to handle complex migration scenarios and how to use Flask-Migrate in a production environment.
id
, username
, and password
fields.email
field to the User model and create a migration for this change.For further practice, consider setting up Flask-Migrate in an existing Flask project, and experiment with different types of schema changes, such as adding tables, deleting columns, and renaming fields.