Welcome to our Flask Migrations tutorial! In this lesson, we'll guide you through the process of managing database schema changes in your Flask applications using the Flask-Migrate extension. By the end, you'll be able to handle database migrations with confidence, making your applications more robust and ready for real-world projects. 🎉
Flask-Migrate is an extension for Flask that helps manage database schema changes in your applications. It generates SQL migrations scripts, which are small scripts to update the database schema, and keeps track of the changes made to your application's database.
Using Flask-Migrate offers several benefits, including:
To use Flask-Migrate in your project, follow these steps:
pip install Flask-Migratefrom flask_migrate import Migrate
app = Flask(__name__)
migrate = Migrate(app, db) # db is your SQLAlchemy database objectTo create a new migration, use the migrate command followed by the make subcommand:
flask db migrate -m "Initial migration"This command will create a new migration file in the migrations directory. The migration file contains the SQL necessary to apply the changes to your database schema.
To apply a migration to your database, use the upgrade subcommand:
flask db upgradeIf you need to rollback a migration, use the downgrade subcommand:
flask db downgrade -n 1Replace 1 with the number of migrations you want to rollback.
What command creates a new migration in Flask-Migrate?
Let's create a simple application with two tables: User and Post.
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True)
password = db.Column(db.String(100))
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db.init_app(app)
migrate.init_app(app, db)Now, create a new migration:
flask db migrate -m "Create User and Post tables"Apply the migration:
flask db upgradeThat's it! You've created and applied a migration in Flask-Migrate.
What is the command to create a new migration in Flask-Migrate?
Happy coding! 🎉