FlaskMigrate is a Flask extension that provides a simple command - line interface for Alembic. It allows you to perform database migrations directly from your Flask application.
Alembic is a database migration tool for SQLAlchemy. It maintains a version history of database schema changes, allowing you to upgrade or downgrade the database schema as needed.
Migration scripts are Python files generated by Alembic. Each migration script represents a specific change to the database schema, such as creating a new table or adding a column to an existing table.
First, you need to install FlaskMigrate and its dependencies. You can use pip
to install them:
pip install Flask-Migrate Flask-SQLAlchemy
Here is a simple example of setting up FlaskMigrate in a Flask application:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# Initialize Flask app
app = Flask(__name__)
# Configure the database URI
app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///app.db'
# Initialize SQLAlchemy
db = SQLAlchemy(app)
# Initialize FlaskMigrate
migrate = Migrate(app, db)
# Define a simple model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
if __name__ == '__main__':
app.run(debug=True)
In this code:
Flask
, SQLAlchemy
, and Migrate
.SQLAlchemy
and FlaskMigrate
.User
model.Before you can start creating migration scripts, you need to initialize the migration repository:
flask db init
This command creates a migrations
directory in your project, which stores all the migration scripts and configuration files.
After making changes to your models, you can generate a new migration script:
flask db migrate -m "Create User table"
The -m
option is used to provide a message describing the migration. Alembic analyzes the changes in your models and generates a new migration script in the migrations/versions
directory.
To apply the generated migration scripts to the database, use the following command:
flask db upgrade
This command upgrades the database schema to the latest version.
If you need to revert a migration, you can use the downgrade
command:
flask db downgrade
This command downgrades the database schema to the previous version.
Let’s say we want to add a new column email
to the User
model:
#... previous code...
# Define a simple model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
email = db.Column(db.String(120))
#... rest of the code...
Then we generate a new migration script:
flask db migrate -m "Add email column to User table"
And apply it to the database:
flask db upgrade
If you have multiple developers working on the same project, there may be conflicts in the migration history. To avoid this, make sure everyone pulls the latest migration scripts from the version control system before running flask db upgrade
.
When making significant changes to the database schema, such as dropping a table or a column, there is a risk of data loss. Always backup your data before performing such migrations.
Sometimes, the generated migration scripts may contain errors. You need to manually edit the migration scripts to fix these errors. Make sure to test the migration scripts in a development or staging environment before applying them to the production database.
When generating migration scripts, use clear and descriptive messages. This makes it easier to understand the purpose of each migration in the future.
Before applying migrations to the production database, test them in a staging environment that closely resembles the production environment. This helps to catch any potential issues early.
Keep your migration scripts under version control. This allows you to track changes to the database schema over time and collaborate with other developers effectively.
FlaskMigrate is a valuable tool for managing database migrations in Flask applications. By understanding the core concepts, typical usage scenarios, common pitfalls, and best practices, you can use FlaskMigrate effectively to handle database schema changes in a version - controlled and reliable way. Whether you are a beginner or an experienced developer, FlaskMigrate can simplify the process of managing your application’s database.