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.
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)
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.
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.
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.
Apply the migration to the database using the following command:
flask db upgrade
This creates the User table in your database.
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
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
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.
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.