Databases with Flask-SQLAlchemy: Storing Data Persistently
6 min read
Databases with Flask-SQLAlchemy: Storing Data Persistently 💾
Welcome to the world of databases with Flask! So far, our Flask applications have had a bit of a memory problem. Every time we restart the server, any data generated is gone forever. To build truly useful applications, we need a way to store data persistently. This is where databases come in, and to interact with them in a Pythonic way, we'll be using Flask-SQLAlchemy.
1. Introduction to ORMs and Configuring Flask-SQLAlchemy
The Problem: Writing raw SQL queries can be tedious and prone to errors. It also tightly couples our application to a specific type of database (like SQLite, PostgreSQL, etc.). If we wanted to switch databases, we'd have to rewrite all of our queries. Imagine having to learn a completely new dialect every time you visit a different region—that's what it can feel like for a developer working with different SQL databases!
The Solution: Object-Relational Mappers (ORMs)
An ORM, like SQLAlchemy, is a library that lets you interact with your database using Python objects instead of raw SQL. This means you can define your database tables as Python classes, and the ORM will handle the translation to SQL behind the scenes. This makes your code more readable, less error-prone, and database-agnostic.
Flask-SQLAlchemy: The Bridge Between Flask and SQLAlchemy
Flask-SQLAlchemy is a Flask extension that makes it even easier to use SQLAlchemy with your Flask application. It handles a lot of the boilerplate configuration and session management for you.
Getting Started: Installation and Configuration
First things first, let's get everything installed. Open up your terminal and, with your virtual environment activated, run the following command:
pip install Flask-SQLAlchemyNow, let's configure Flask-SQLAlchemy in our Flask application.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# This is the configuration for the database URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)
@app.route('/')
def index():
return '<h1>Hello, World!</h1>'In the code above, SQLALCHEMY_DATABASE_URI is the connection string that tells SQLAlchemy where our database is located. Here, we're using SQLite, a simple file-based database that's great for development.
2. Defining Database Models: Tables, Columns, and Types
The Problem: How do we tell our application what our database tables should look like? What kind of data will each column hold?
The Solution: Database Models
In the world of ORMs, a "model" is a Python class that represents a table in your database. This class will contain attributes that map to the columns of the table.
Let's define a simple User model:
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}>'Let's break this down:
class User(db.Model):Our model class inherits fromdb.Model, which is the base model provided by Flask-SQLAlchemy.id = db.Column(db.Integer, primary_key=True): This defines a column namedidthat will store integers.primary_key=Truedesignates this column as the primary key, which uniquely identifies each record in the table.username = db.Column(db.String(80), unique=True, nullable=False): This creates ausernamecolumn that stores strings with a maximum length of 80 characters.unique=Trueensures that every username is unique, andnullable=Falsemeans this field cannot be empty.email = db.Column(db.String(120), unique=True, nullable=False): Similar to the username, this column stores the user's email address.__repr__: This is an optional but helpful method that defines how instances of this class will be represented when printed.
Creating the Tables
Defining the model class doesn't actually create the table in the database. For that, we need to use the db.create_all() method. You'll typically do this in a Python shell or a one-time script.
with app.app_context():
db.create_all()This command will check for all classes that inherit from db.Model and create the corresponding tables in the database if they don't already exist.
3. CRUD Operations: Create, Read, Update, and Delete in Python
Now that we have our database and a model, let's learn how to perform the four fundamental operations of data management: Create, Read, Update, and Delete (CRUD).
The "Session": Your Staging Area for Database Changes
Imagine you have a shopping cart online. You can add items, remove them, and change quantities. These changes aren't final until you click "checkout." SQLAlchemy's "session" works in a similar way. It's a temporary area where you can stage changes to your database. Once you're happy with your changes, you "commit" them to make them permanent.
Create: Adding New Data
To add a new user to our database, we create an instance of our User model and add it to the session.
from your_app import db, User
# Create a new user
new_user = User(username='john_doe', email='[email protected]')
# Add the new user to the session
db.session.add(new_user)
# Commit the session to save the changes to the database
db.session.commit()Read: Querying the Database
To retrieve data, we use the query attribute on our model class.
# Get all users
all_users = User.query.all()
# Get a single user by their ID
user = User.query.get(1)
# Filter users by a specific attribute
john = User.query.filter_by(username='john_doe').first()Update: Modifying Existing Data
To update a record, you first need to retrieve it, then modify its attributes, and finally commit the changes.
user_to_update = User.query.get(1)
user_to_update.email = '[email protected]'
db.session.commit()Delete: Removing Data
Deleting a record follows a similar pattern: fetch the record, tell the session to delete it, and then commit.
user_to_delete = User.query.get(1)
db.session.delete(user_to_delete)
db.session.commit()4. Database Migrations: Evolving Your Schema with Flask-Migrate
The Problem: What happens when you need to change your database structure after you've already created it and have data in it? For example, what if you want to add a new password column to your User model? Simply running db.create_all() again won't work, as it doesn't modify existing tables.
The Solution: Database Migrations with Flask-Migrate
Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using a tool called Alembic. Think of it like version control (like Git) for your database schema. It allows you to make changes to your models and then generate "migration scripts" that can be applied to your database to update it.
Getting Started with Flask-Migrate
First, install Flask-Migrate:
pip install Flask-MigrateNext, integrate it into your Flask application:
from flask_migrate import Migrate
# After initializing your app and db
migrate = Migrate(app, db)The Migration Workflow
There are three main commands you'll use:
flask db init: This command is run once to initialize the migration environment. It will create amigrationsfolder in your project.flask db migrate -m "A short message describing the changes": This command generates a new migration script based on the changes it detects in your models.flask db upgrade: This command applies the latest migration script to your database, updating the schema.
Let's walk through an example. Suppose we want to add a password_hash column to our User model.
Step 1: Update your model
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)
password_hash = db.Column(db.String(128))Step 2: Generate the migration script
In your terminal, run:
flask db migrate -m "Add password_hash to User model"This will create a new file in the migrations/versions directory containing the Python code to add the new column.
Step 3: Apply the migration
flask db upgradeAnd that's it! Your database schema is now up-to-date with your models, without losing any of your existing data.
References for Extra Reading
- Flask-SQLAlchemy Documentation: https://flask-sqlalchemy.palletsprojects.com/
- SQLAlchemy Documentation: https://www.sqlalchemy.org/
- Flask-Migrate Documentation: https://flask-migrate.readthedocs.io/
Challenge
You are building the backend for an e-commerce platform using Flask and Flask-SQLAlchemy. Your task is to set up the database configuration, define the data model for a Product, and implement the core functions for Create, Read, Update, and Delete (CRUD) operations.
Requirements:
- Configuration: Configure the Flask application to use a temporary, in-memory SQLite database by setting the
SQLALCHEMY_DATABASE_URI. - Model Definition: Create a
Productmodel that inherits fromdb.Model. It must have the following columns:id: An integer that serves as the primary key.name: A string with a maximum length of 100 characters. It must be unique and cannot be null.price: A floating-point number representing the price. It cannot be null.stock_quantity: An integer representing the number of items in stock. It cannot be null.
- CRUD Functions: Complete the implementation for the following four functions:
add_product(name, price, stock_quantity): This function should create a newProductinstance, add it to the database session, and commit the transaction.get_product_by_id(product_id): This function should query the database and return theProductinstance corresponding to the givenproduct_id.update_product_stock(product_id, new_quantity): This function should find a product by its ID, update itsstock_quantityto thenew_quantity, and commit the change.delete_product(product_id): This function should find a product by its ID, delete it from the database session, and commit the transaction.
Fill in the missing parts of the provided initialCode. You do not need to worry about creating the tables (db.create_all()) or managing the application context.
Expected result
Your solution should correctly configure the database URI, define the Product model with the specified columns and constraints, and fully implement the four CRUD functions using the Flask-SQLAlchemy session and query APIs.
Here is an example of a correct implementation:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# 1. Initialize Flask App and configure the database
app = Flask(__name__)
# Configure the app with the 'SQLALCHEMY_DATABASE_URI' for an in-memory SQLite database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)
# 2. Define the Product model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
price = db.Column(db.Float, nullable=False)
stock_quantity = db.Column(db.Integer, nullable=False)
# 3. Implement CRUD functions
def add_product(name, price, stock_quantity):
"""Creates a new product, adds it to the session, and commits."""
new_product = Product(name=name, price=price, stock_quantity=stock_quantity)
db.session.add(new_product)
db.session.commit()
def get_product_by_id(product_id):
"""Retrieves a single product by its primary key."""
return Product.query.get(product_id)
def update_product_stock(product_id, new_quantity):
"""Finds a product, updates its stock, and commits the change."""
product_to_update = Product.query.get(product_id)
product_to_update.stock_quantity = new_quantity
db.session.commit()
def delete_product(product_id):
"""Finds a product, deletes it from the session, and commits."""
product_to_delete = Product.query.get(product_id)
db.session.delete(product_to_delete)
db.session.commit()