Skip to content
Happy Programming Guide
Start learning
Python

How to Build a CRUD App with Flask and SQLAlchemy

A complete create, read, update and delete application in Flask: models, forms, templates, validation and the structure that keeps it maintainable.

A processor chip photographed up close

CRUD stands for create, read, update and delete — the four things almost every application does with data. This guide builds a complete Flask application doing all four, with SQLAlchemy for the database, proper validation, and a structure that will still make sense when the project grows past one file.

Setting up#

Terminal
python -m venv .venv
source .venv/bin/activate        # .venv\Scripts\activate on Windows

pip install flask flask-sqlalchemy flask-migrate python-dotenv
pip freeze > requirements.txt
Output
app/
    __init__.py
    models.py
    routes.py
    templates/
        base.html
        products/
            list.html
            form.html
config.py
.env
run.py

Configuration and the application factory#

Python
# config.py
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent


class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY", "change-me-in-production")
    SQLALCHEMY_DATABASE_URI = os.environ.get(
        "DATABASE_URL", f"sqlite:///{BASE_DIR / 'app.db'}"
    )
    SQLALCHEMY_TRACK_MODIFICATIONS = False
Python
# app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)

    from app.routes import bp
    app.register_blueprint(bp)

    return app

The factory pattern matters more than it looks. Creating the app inside a function means tests can build one with a different configuration — an in-memory database, for instance — without touching production settings.

Python
# run.py
from app import create_app

app = create_app()
Terminal
flask --app run run --debug

The model#

Python
# app/models.py
from datetime import datetime, timezone
from app import db


class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), nullable=False, index=True)
    price = db.Column(db.Numeric(10, 2), nullable=False)
    description = db.Column(db.Text, default="")
    created_at = db.Column(
        db.DateTime, default=lambda: datetime.now(timezone.utc), nullable=False
    )

    def __repr__(self):
        return f"<Product {self.id} {self.name}>"

Two details. Numeric rather than Float for money, because binary floating point cannot represent decimal fractions exactly and the errors accumulate. And the default is a lambda, so it is evaluated at insert time rather than once when the module loads.

Terminal
flask --app run db init
flask --app run db migrate -m "add products"
flask --app run db upgrade

Read the generated migration before applying it. The tool infers the change and occasionally guesses wrong — a rename can come out as a drop and an add, which loses data.

Read: listing and showing#

Python
# app/routes.py
from flask import Blueprint, render_template, request, redirect, url_for, flash, abort
from sqlalchemy import select
from app import db
from app.models import Product

bp = Blueprint("products", __name__, url_prefix="/products")


@bp.route("/")
def index():
    page = request.args.get("page", 1, type=int)
    search = request.args.get("q", "").strip()

    query = select(Product).order_by(Product.name)
    if search:
        query = query.where(Product.name.ilike(f"%{search}%"))

    products = db.paginate(query, page=page, per_page=20, error_out=False)

    return render_template("products/list.html", products=products, search=search)


@bp.route("/<int:product_id>")
def show(product_id):
    product = db.get_or_404(Product, product_id)
    return render_template("products/show.html", product=product)

get_or_404 returns a proper 404 rather than crashing on a missing id. The <int:...> converter means a non-numeric id never reaches your code at all.

Create#

Python
from decimal import Decimal, InvalidOperation


def validate(form):
    errors = {}

    name = form.get("name", "").strip()
    if not name:
        errors["name"] = "Name is required"
    elif len(name) > 120:
        errors["name"] = "Name must be 120 characters or fewer"

    try:
        price = Decimal(form.get("price", "").strip())
        if price <= 0:
            errors["price"] = "Price must be greater than zero"
    except (InvalidOperation, TypeError):
        price = None
        errors["price"] = "Price must be a number"

    return {"name": name, "price": price,
            "description": form.get("description", "").strip()}, errors


@bp.route("/new", methods=["GET", "POST"])
def create():
    if request.method == "POST":
        data, errors = validate(request.form)

        if errors:
            return render_template("products/form.html",
                                   product=data, errors=errors), 422

        product = Product(**data)
        db.session.add(product)
        db.session.commit()

        flash(f"Created {product.name}", "success")
        return redirect(url_for("products.index"))

    return render_template("products/form.html", product={}, errors={})

Update#

Python
@bp.route("/<int:product_id>/edit", methods=["GET", "POST"])
def edit(product_id):
    product = db.get_or_404(Product, product_id)

    if request.method == "POST":
        data, errors = validate(request.form)

        if errors:
            return render_template("products/form.html",
                                   product=data, errors=errors), 422

        product.name = data["name"]
        product.price = data["price"]
        product.description = data["description"]
        db.session.commit()

        flash("Saved", "success")
        return redirect(url_for("products.show", product_id=product.id))

    return render_template("products/form.html", product=product, errors={})

Note there is no db.session.add() here. SQLAlchemy tracks the loaded object, so assigning to its attributes is enough — commit() works out what changed and generates an UPDATE touching only those columns.

Delete#

Python
@bp.route("/<int:product_id>/delete", methods=["POST"])
def delete(product_id):
    product = db.get_or_404(Product, product_id)
    name = product.name

    db.session.delete(product)
    db.session.commit()

    flash(f"Deleted {name}", "success")
    return redirect(url_for("products.index"))

Templates#

HTML
<!-- app/templates/base.html -->
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{% block title %}Products{% endblock %}</title>
</head>
<body>
  {% with messages = get_flashed_messages(with_categories=true) %}
    {% for category, message in messages %}
      <p class="flash flash--{{ category }}">{{ message }}</p>
    {% endfor %}
  {% endwith %}

  {% block content %}{% endblock %}
</body>
</html>
HTML
<!-- app/templates/products/list.html -->
{% extends "base.html" %}

{% block content %}
  <h1>Products</h1>

  <form method="get">
    <input name="q" value="{{ search }}" placeholder="Search">
    <button>Search</button>
  </form>

  <p><a href="{{ url_for('products.create') }}">Add a product</a></p>

  <ul>
    {% for product in products %}
      <li>
        <a href="{{ url_for('products.show', product_id=product.id) }}">
          {{ product.name }}
        </a>
        — {{ "%.2f"|format(product.price) }}

        <form method="post"
              action="{{ url_for('products.delete', product_id=product.id) }}"
              onsubmit="return confirm('Delete this product?')">
          <button>Delete</button>
        </form>
      </li>
    {% else %}
      <li>No products yet.</li>
    {% endfor %}
  </ul>

  {% if products.pages > 1 %}
    <nav>
      {% for page in products.iter_pages() %}
        {% if page %}
          <a href="{{ url_for('products.index', page=page, q=search) }}">{{ page }}</a>
        {% else %}
          …
        {% endif %}
      {% endfor %}
    </nav>
  {% endif %}
{% endblock %}

Jinja2 escapes output by default, which is what protects you from cross-site scripting. The {% else %} clause on a for loop is a small Jinja convenience — it runs when the collection is empty.

Testing#

Python
import pytest
from app import create_app, db
from config import Config


class TestConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"


@pytest.fixture
def client():
    app = create_app(TestConfig)
    with app.app_context():
        db.create_all()
        yield app.test_client()
        db.drop_all()


def test_create_and_list(client):
    response = client.post("/products/new",
                           data={"name": "Pen", "price": "1.50"},
                           follow_redirects=True)
    assert response.status_code == 200
    assert b"Pen" in response.data


def test_rejects_blank_name(client):
    response = client.post("/products/new", data={"name": "", "price": "1.50"})
    assert response.status_code == 422

An in-memory database means the tests are fast and leave nothing behind. This is what the application factory was for.

Before deploying#

  • Set SECRET_KEY from the environment — sessions are signed with it
  • Turn off debug mode; its interactive debugger allows arbitrary code execution
  • Add CSRF protection with Flask-WTF for every form
  • Move from SQLite to PostgreSQL for anything with concurrent writers
  • Run behind a real server: gunicorn "run:app"

Questions people ask#

Flask or Django?

Django gives you an admin interface, authentication and an ORM out of the box — less to assemble. Flask gives you a smaller core and more choices. For learning how the pieces fit together, Flask is more instructive.

Do I need Flask-WTF?

Not for a small form, and it is worth adding early: it handles CSRF tokens, validation and re-rendering with errors, all of which you would otherwise write yourself.

Why use migrations rather than create_all?

create_all only creates tables that do not exist — it will not alter an existing one. The moment you add a column to a database with data in it, you need migrations.

Should I use the new SQLAlchemy 2.0 style?

Yes for new code — select() with db.session.execute() is the current API. The older Model.query style still works and appears in most tutorials, so you will meet both.

Where to go next#

Python security, before this app reaches the internetRead next

Keep reading

Python

The List Data Type in Python

Creating, indexing, slicing and modifying lists, the methods worth knowing, and the copying and sorting traps that catch beginners.

5 min read

Python

Python asyncio for Beginners

async and await let one thread handle many waiting tasks at once. What that means, when it helps, a working example that…

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *