Welcome back! Today, we're diving into a crucial aspect of web development - Database Migrations in Production with Flask. Let's get started!
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.
First, let's set up a basic Flask application with SQLAlchemy as the ORM (Object-Relational Mapping) library:
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.
Now, let's create a simple model for a User:
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}>'Alembic is a tool for managing database migrations in Flask. It allows you to create, version, and apply migrations to your database.
First, install Alembic using pip:
pip install alembic
Next, create the Alembic environment and generate the initial migration script:
alembic init alembic
cd alembic
alembic init -m -d ..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:
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')Finally, let's apply the migration to our database:
cd ..
alembic upgrade headYou'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.
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! 🚀