Database Migrations in Flask: Step-by-Step Guide
Introduction
In this article, we will explore how to use Flask-Migrate for schema changes, as well as applying and managing migrations in a Flask application.
Step 1: Setting Up Flask and Flask-Migrate
First, ensure you have Flask and Flask-Migrate installed. You can install them using pip:
pip install flask flask_sqlalchemy flask-migrate
Set up your Flask application and configure SQLAlchemy:
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)
Step 2: Define a Model
Create a simple model, such as a User model:
class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False)
At this stage, your database is not yet created. Flask-Migrate will handle this.
Step 3: Initialize Flask-Migrate
Initialize Flask-Migrate in your project by running the following command in the terminal:
flask db init
This creates a migrations
folder to track migration files.
Step 4: Create the First Migration
Generate the migration script to create the User table:
flask db migrate -m "Initial migration"
This creates a new migration file in the migrations/versions
folder.
Step 5: Apply the Migration
Apply the migration to the database using the following command:
flask db upgrade
This creates the User table in your database.
Step 6: Modifying the Schema
To demonstrate schema changes, add a new column to the User model:
class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) age = db.Column(db.Integer)
Generate a new migration to reflect this change:
flask db migrate -m "Add age column to User"
Apply the migration to update the database schema:
flask db upgrade
Step 7: Managing Migrations
To view the current state of migrations, use:
flask db history
To downgrade to a previous migration, use:
flask db downgrade
For example, to downgrade one step:
flask db downgrade -1
Step 8: Rollback Changes
If you need to undo a migration completely, you can use the downgrade command to revert all changes and then remove the migration files.
flask db downgrade base
After downgrading, you can delete the migration files in the migrations
folder.
Conclusion
Flask-Migrate simplifies database schema changes by providing tools to generate and manage migrations. By following these steps, you can efficiently handle database changes in your Flask projects.