Flask / Flask Models and Databases

Migration Management

In the Migration Management tutorial, we will discuss how to handle database schema changes over time using Flask-Migrate, an extension that handles SQLAlchemy database migrations.

Tutorial 3 of 4 4 resources in this section

Section overview

4 resources

Explores Flask models, SQLAlchemy ORM, and database integration.

1. Introduction

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

2. Step-by-Step Guide

Setting up Flask-Migrate

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.

Creating Database Migrations

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.

Applying Database Migrations

To apply the migrations, we use the flask db upgrade command:

flask db upgrade

Rolling Back Migrations

To undo migrations, we use the flask db downgrade command:

flask db downgrade

3. Code Examples

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

4. Summary

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.

5. Practice Exercises

  1. Set up Flask-Migrate in a new Flask project.
  2. Create a User model with id, username, and password fields.
  3. Add an 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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help