Database Migrations in Production with Flask

beginner
16 min

Database Migrations in Production with Flask

Welcome back! Today, we're diving into a crucial aspect of web development - Database Migrations in Production with Flask. Let's get started!

What are Database Migrations? 💡

Database migrations are the process of updating a database schema in a controlled and automated way. They help manage changes in the database structure, such as adding or removing tables, columns, or data types, while keeping your application running smoothly.

Why are Database Migrations important? 📝

  1. Version control: Migrations allow you to keep track of changes made to your database schema over time, making it easier to rollback changes if necessary.
  2. Consistency: Migrations ensure that all of your databases are in the same state, even when deployed on different servers or environments.
  3. Code-first approach: By defining the database schema in your code, you can easily manage and version your schema alongside your application code.

Setting Up Flask and SQLAlchemy ✅

First, let's set up a basic Flask application with SQLAlchemy as the ORM (Object-Relational Mapping) library:

python
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' db = SQLAlchemy(app) if __name__ == '__main__': db.create_all() app.run(debug=True)

In this example, we create a SQLite database called db.sqlite3.

Creating a Simple Model 🎯

Now, let's create a simple model for a User:

python
class User(db.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) def __repr__(self): return f'<User {self.username}>'

Database Migrations with Alembic 💡

Alembic is a tool for managing database migrations in Flask. It allows you to create, version, and apply migrations to your database.

Installing Alembic

First, install Alembic using pip:

pip install alembic

Initializing Alembic

Next, create the Alembic environment and generate the initial migration script:

bash
alembic init alembic cd alembic alembic init -m -d ..

Defining the Migration

Now, let's create our first migration script. In the migrations folder, open the file versions/0001_create_users.py. You'll see a skeleton script that we'll fill in:

python
from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=80), nullable=False), sa.Column('email', sa.String(length=120), nullable=False), sa.PrimaryKeyConstraint('id'), ) def downgrade(): op.drop_table('users')

Applying the Migration

Finally, let's apply the migration to our database:

bash
cd .. alembic upgrade head

Wrapping Up ✅

You've just created your first database migration with Flask and Alembic! Migrations are essential for managing your application's database schema in a controlled and automated way.

Quiz 📝

Quick Quiz
Question 1 of 1

What is the purpose of using Alembic in Flask projects?

Keep learning and coding! In the next lesson, we'll dive deeper into working with migrations and learn how to version and rollback changes. See you then! 🚀