0
0
Flaskframework~5 mins

Database migrations with Flask-Migrate

Choose your learning style9 modes available
Introduction

Database migrations help you change your database structure safely as your app grows. Flask-Migrate makes this easy by tracking and applying these changes step-by-step.

When you add a new column to a database table in your Flask app.
When you rename or remove a database table or column.
When you want to share database changes with your team.
When deploying updates to your app's database on a server.
When you want to keep your database schema versioned and organized.
Syntax
Flask
from flask_migrate import Migrate

migrate = Migrate(app, db)

# Then use command line:
# flask db init
# flask db migrate -m "message"
# flask db upgrade

Flask-Migrate works with Flask and SQLAlchemy to manage database changes.

Use the command line commands to create and apply migrations.

Examples
Initializes the migrations folder to start tracking database changes.
Flask
flask db init
Creates a new migration script describing the changes you made to your models.
Flask
flask db migrate -m "Add user email column"
Applies the migration changes to your actual database.
Flask
flask db upgrade
Sample Program

This Flask app sets up a User model and uses Flask-Migrate to handle database changes. You run commands to create migration files and update the database.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)

# After saving this, run in terminal:
# flask db init
# flask db migrate -m "Create user table"
# flask db upgrade

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always review migration scripts before applying them to avoid unwanted changes.

Keep your migration files in version control to share with your team.

Use descriptive messages with flask db migrate -m "message" to remember what each migration does.

Summary

Flask-Migrate helps manage database changes safely and easily.

Use command line commands to create and apply migrations.

Keep your database schema organized as your app grows.