Flask-Migrate is an extension for Flask that simplifies the process of creating and migrating database tables using SQLAlchemy. In this guide, we'll explore how to set up Flask-Migrate, create and manage database tables, and perform migrations to keep your database schema up-to-date.
Step 1: Setting Up Your Flask Application
Before you can work with Flask-Migrate, make sure you have a Flask application with SQLAlchemy configured. If not, you can create a basic Flask app like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
Ensure you have Flask-SQLAlchemy and Flask-Migrate installed, and specify the database URI for your SQLite database.
Step 2: Creating a Model
To define a model, create a Python class representing a table in your database. Here's an example of a simple 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)
In this example, we define a "User" model with three fields: "id," "username," and "email." The model class inherits from
db.Model, and the fields are defined as class attributes.
Step 3: Creating Initial Migrations
Run the following commands in your terminal to create an initial migration for your database schema:
flask db init
flask db migrate -m "initial migration"
This initializes the migration environment and creates a migration script for the initial state of your database.
Step 4: Applying Migrations
To apply the migrations and create database tables, run the following command:
flask db upgrade
This will execute the migration script and create the database tables based on your defined models.
Step 5: Performing Database Operations
With your models and tables in place, you can interact with the database using SQLAlchemy methods, just as in previous examples.
Step 6: Making Schema Changes
If you need to make changes to your database schema, create a new migration with:
flask db migrate -m "description of changes"
And apply the changes with:
flask db upgrade
Flask-Migrate simplifies the process of creating, managing, and migrating database tables in Flask applications. By following these steps, you can keep your database schema up-to-date and effectively manage your data models.