Web frameworks · Intermediate · 24 min
Store data in a Flask app with SQLAlchemy and an app factory
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · Flask 3.1 · Flask-SQLAlchemy 3.1 · SQLAlchemy 2.1 · pytest 9.2
You will build a Flask 3.1 guestbook that keeps its entries in a database through Flask-SQLAlchemy, organised with an application factory and a blueprint, and covered by pytest tests that run against a throwaway SQLite file.
On this page
A guestbook that keeps its entries in a Python list forgets everything when the server restarts. In this tutorial you give it a database. You use Flask-SQLAlchemy, the extension that connects Flask to SQLAlchemy, a long-established Python database toolkit, and you write models in the SQLAlchemy 2 style, where each column has a Python type the editor and type checker understand.
You also change how the app is put together. Instead of one app.py with a global app object, the code becomes a package with an application factory, a function that builds and returns a configured app, and a blueprint, a group of routes registered on that app. The factory is what lets tests create a fresh app pointing at a temporary database, and lets production point the same code at PostgreSQL with one environment variable.
The app starts from an empty folder, so you can follow it without the code from the first Flask tutorial. If you finished that one, the routes and templates will look familiar. It uses uv for the project and its environment, as in the Python series.
Step 1 · Create the project and install the packages
Make a project folder and add Flask, Flask-SQLAlchemy and SQLAlchemy, plus pytest as a development dependency. Each range allows patch releases of the version this tutorial uses and nothing newer, so a new minor release cannot change behaviour under you:
mkdir -p ~/flask-guestbook-demo
cd ~/flask-guestbook-demo
uv init --no-package
rm -f main.py
uv add "flask>=3.1,<3.2" "flask-sqlalchemy>=3.1,<3.2" "sqlalchemy>=2.1,<2.2"
uv add --dev "pytest>=9.2,<10"
mkdir -p guestbook/templates testsuv init writes a main.py you do not need, so the commands remove it. The app lives in a guestbook package, with its templates beside it, and the tests in their own folder.
Check it worked
uv run python -c "from importlib.metadata import version; [print(p, version(p)) for p in ('flask', 'flask-sqlalchemy', 'sqlalchemy', 'pytest')]"You see four lines, something like flask 3.1.3, flask-sqlalchemy 3.1.1, sqlalchemy 2.1.9 and pytest 9.2.0. A later patch release of each is fine.
Step 2 · Define the database and a typed model
Create guestbook/db.py. It holds the one db object the rest of the app imports. It is created without an app, which is the point: the factory attaches it to whichever app it builds. Passing a DeclarativeBase subclass as model_class turns on SQLAlchemy 2's typed models:
cat > guestbook/db.py <<'PY'
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)
PYNow the model. Create guestbook/models.py with one table for entries:
cat > guestbook/models.py <<'PY'
from datetime import datetime
from sqlalchemy import String, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from .db import db
class Entry(db.Model):
__tablename__ = "entries"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(80))
message: Mapped[str] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(server_default=func.now())
def __repr__(self) -> str:
return f"<Entry {self.id} by {self.name!r}>"
PYEach Mapped[...] annotation does two jobs. It tells SQLAlchemy the column type (int becomes INTEGER, datetime becomes DATETIME) and whether the column may be empty: a plain Mapped[str] is NOT NULL, and Mapped[str | None] would allow NULL. String(80) and Text narrow the type where the default is not what you want. server_default=func.now() asks the database to fill in the time when a row is inserted, so the app never has to. SQLite records that time in UTC, so the entry page labels it UTC: a reader in Lagos (UTC+1) sees a time one hour behind the wall clock.
Check it worked
Ask SQLAlchemy what table it built from the class:
uv run python -c "from guestbook.models import Entry; print([(c.name, str(c.type), c.nullable) for c in Entry.__table__.columns])"The output lists four columns, all with False for nullable: ('id', 'INTEGER', False), ('name', 'VARCHAR(80)', False), ('message', 'TEXT', False) and ('created_at', 'DATETIME', False).
Step 3 · Write the blueprint and its templates
Create guestbook/views.py. The blueprint, called entries, has two routes: the guestbook page, which lists entries and accepts new ones, and a page for a single entry:
cat > guestbook/views.py <<'PY'
from flask import Blueprint, redirect, render_template, request, url_for
from sqlalchemy import select
from .db import db
from .models import Entry
bp = Blueprint("entries", __name__)
@bp.route("/", methods=["GET", "POST"])
def index():
error = None
if request.method == "POST":
name = request.form.get("name", "").strip()
message = request.form.get("message", "").strip()
if not name or not message:
error = "Add your name and a message."
elif len(name) > 80:
error = "Keep your name to 80 characters."
else:
db.session.add(Entry(name=name, message=message))
db.session.commit()
return redirect(url_for("entries.index"), code=303)
stmt = select(Entry).order_by(Entry.id.desc()).limit(50)
entries = db.session.scalars(stmt).all()
status = 400 if error else 200
return render_template("index.html", entries=entries, error=error), status
@bp.get("/entries/<int:entry_id>")
def show(entry_id):
entry = db.get_or_404(Entry, entry_id, description="No guestbook entry with that number.")
return render_template("entry.html", entry=entry)
PYWhat the database code does:
db.session.add(...)stages a new row anddb.session.commit()writes it. Until the commit, nothing is saved. Flask-SQLAlchemy gives each request its own session and cleans it up when the request ends.select(Entry).order_by(...).limit(50)builds a query as a Python object, the SQLAlchemy 2 way.db.session.scalars(stmt).all()runs it and returns a list ofEntryobjects, newest first. The values from the form never become part of the SQL text: SQLAlchemy sends them as bound parameters, which is what protects the app from SQL injection.db.get_or_404(Entry, entry_id)loads one row by primary key, or stops the request with a 404 response if there is none. The<int:...>converter in the route already turns away anything that is not a number.- After a successful
POST, the view answers with a303 See Otherredirect, as in the first Flask tutorial, so the browser loads the page again with a GET and refreshing does not sign the guestbook twice. Withoutcode=303, Flask'sredirectsends302 Found. A form with a missing field gets the page back with a message and a400status.
Now the templates. base.html is the shared layout, and the other two fill in its content block:
cat > guestbook/templates/base.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Guestbook{% endblock %}</title>
</head>
<body>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
HTML
cat > guestbook/templates/index.html <<'HTML'
{% extends "base.html" %}
{% block content %}
<h1>Guestbook</h1>
{% if error %}<p role="alert">{{ error }}</p>{% endif %}
<form method="post">
<label>Name <input name="name" maxlength="80" required></label>
<label>Message <textarea name="message" required></textarea></label>
<button type="submit">Sign</button>
</form>
<ul>
{% for entry in entries %}
<li><a href="{{ url_for('entries.show', entry_id=entry.id) }}">{{ entry.name }}</a>: {{ entry.message }}</li>
{% else %}
<li>No entries yet.</li>
{% endfor %}
</ul>
{% endblock %}
HTML
cat > guestbook/templates/entry.html <<'HTML'
{% extends "base.html" %}
{% block title %}Entry {{ entry.id }} · Guestbook{% endblock %}
{% block content %}
<h1>{{ entry.name }}</h1>
<p>{{ entry.message }}</p>
<p>Signed {{ entry.created_at.strftime("%d %B %Y at %H:%M") }} UTC</p>
<p><a href="{{ url_for('entries.index') }}">Back to the guestbook</a></p>
{% endblock %}
HTMLInside a blueprint, endpoint names carry the blueprint's name as a prefix, so url_for takes entries.index and entries.show, not index and show. Jinja escapes every {{ ... }} value, so a message containing HTML shows as text.
Check it worked
uv run python -c "from guestbook.views import bp; print(bp.name, bp.import_name)"
ls guestbook/templatesThe first line is entries guestbook.views, and the listing shows base.html, entry.html and index.html.
Step 4 · Build the app factory and create the tables
Create guestbook/__init__.py. The create_app function makes the Flask app, loads its settings, attaches db, registers the blueprint and adds an init-db command:
cat > guestbook/__init__.py <<'PY'
import click
from flask import Flask
from .db import db
def create_app(test_config=None):
app = Flask(__name__)
app.config.from_mapping(
SQLALCHEMY_DATABASE_URI="sqlite:///guestbook.sqlite",
)
if test_config is None:
app.config.from_prefixed_env()
else:
app.config.update(test_config)
db.init_app(app)
from . import models # noqa: F401 registers the tables on db.metadata
from .views import bp
app.register_blueprint(bp)
@app.cli.command("init-db")
def init_db():
"""Create any tables that do not exist yet."""
db.create_all()
click.echo(f"Tables ready in {db.engine.url}")
return app
PYThe settings come in layers:
from_mappingsets the default: a SQLite file calledguestbook.sqlite. Flask-SQLAlchemy reads a relative SQLite path as relative to the app's instance folder,instance/next to the package, and creates that folder for you. Keep it out of version control, as it holds your data.from_prefixed_env()then reads every environment variable that starts withFLASK_and stores it without the prefix.FLASK_SQLALCHEMY_DATABASE_URIoverrides the database address, andFLASK_SECRET_KEYwould set the secret key if you add sessions or flash messages later. Secrets stay in the environment, never in the code.- Tests pass a
test_configdictionary instead, and the environment is skipped, so a test run can never reach the database a server is configured for.
The settings must be in place before db.init_app(app), because that call reads SQLALCHEMY_DATABASE_URI to create the database engine.
flask --app guestbook finds the create_app function by name and calls it. Use that to create the tables:
uv run flask --app guestbook init-dbdb.create_all() creates tables that are missing and leaves existing ones alone. It does not change a table you have already created, so when a model changes on an app with real data, use a migration tool such as Alembic instead.
Check it worked
The command prints a line like Tables ready in sqlite:////home/you/flask-guestbook-demo/instance/guestbook.sqlite, with your own home folder in the path. The file is there:
ls instanceThe listing shows guestbook.sqlite. Running init-db a second time prints the same line and changes nothing.
Step 5 · Run the app and sign the guestbook
Start the development server in your second terminal, from the project folder, and leave it running. The --debug flag turns on an interactive debugger that can run any Python code on the machine, so never use --debug on a server that other people can reach:
uv run flask --app guestbook run --debugIt prints Running on http://127.0.0.1:5000. --debug reloads the code when you save a file and shows the debugger on errors.
Open http://127.0.0.1:5000/ in your browser and sign the guestbook, or post the form from your first terminal with curl:
curl -s -o /dev/null -w '%{http_code}\n' --data-urlencode 'name=Ada' --data-urlencode 'message=Hello from Lagos' http://127.0.0.1:5000/
curl -s -o /dev/null -w '%{http_code}\n' --data-urlencode 'name=Tunde' --data-urlencode 'message=Ẹ kú àbọ̀' http://127.0.0.1:5000/
curl -s -o /dev/null -w '%{http_code}\n' --data-urlencode 'name=' --data-urlencode 'message=No name' http://127.0.0.1:5000/The second entry is in Yoruba, with tone marks. SQLite stores text as UTF-8, as does a PostgreSQL database created with UTF8 encoding, the default on Ubuntu, so names and messages in any language come back exactly as they were typed.
Check it worked
The three requests print 303, 303 and 400: two entries saved and redirected, and one rejected for the missing name. List the page:
curl -s http://127.0.0.1:5000/ | grep -o '<li>.*</li>'You see two lines, newest first: Tunde's message, then <li><a href="/entries/1">Ada</a>: Hello from Lagos</li>. The rejected entry is not there.
Step 6 · Show one entry, and prove the data survives a restart
Each name links to /entries/<id>, the route that uses get_or_404. Ask for an entry that exists and one that does not:
curl -s http://127.0.0.1:5000/entries/1 | grep -o '<h1>[^<]*</h1>'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/entries/999
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/entries/abcNow the reason for the database. Stop the server with Ctrl+C in the second terminal, then start it again with the same command.
curl -s http://127.0.0.1:5000/ | grep -c '<li><a href'Check it worked
The entry page shows <h1>Ada</h1>. The missing entry returns 404, and /entries/abc also returns 404, because the int converter does not match it. After the restart, the count is 2: both entries came back from instance/guestbook.sqlite. With the in-memory list from the first Flask tutorial, it would be 0.
Step 7 · Test the app with pytest and a temporary database
Tell pytest where the code and tests are. This adds a new section to the end of pyproject.toml:
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
TOMLCreate tests/conftest.py with two fixtures. app calls the factory with a test configuration whose database is a file in pytest's tmp_path, a new empty folder for every test, and creates the tables there. client is Flask's test client, which sends requests to the app without a server:
cat > tests/conftest.py <<'PY'
import pytest
from guestbook import create_app
from guestbook.db import db
@pytest.fixture
def app(tmp_path):
app = create_app({
"TESTING": True,
"SQLALCHEMY_DATABASE_URI": f"sqlite:///{tmp_path / 'test.sqlite'}",
})
with app.app_context():
db.create_all()
yield app
@pytest.fixture
def client(app):
return app.test_client()
PYThen the tests. Each one starts with an empty database, so they do not depend on each other or on the data you added by hand:
cat > tests/test_entries.py <<'PY'
from sqlalchemy import func, select
from guestbook.db import db
from guestbook.models import Entry
def test_empty_guestbook(client):
response = client.get("/")
assert response.status_code == 200
assert b"No entries yet." in response.data
def test_signing_saves_an_entry(client, app):
response = client.post("/", data={"name": "Ada", "message": "Hello from Lagos"})
assert response.status_code == 303
with app.app_context():
entry = db.session.scalars(select(Entry)).one()
assert entry.name == "Ada"
page = client.get("/")
assert b"Hello from Lagos" in page.data
def test_missing_fields_are_rejected(client, app):
response = client.post("/", data={"name": "", "message": "No name"})
assert response.status_code == 400
assert b"Add your name and a message." in response.data
with app.app_context():
assert db.session.scalar(select(func.count(Entry.id))) == 0
def test_html_is_escaped(client):
client.post("/", data={"name": "Eve", "message": "<script>alert(1)</script>"})
page = client.get("/")
assert b"<script>alert(1)</script>" not in page.data
assert b"<script>" in page.data
def test_show_entry_and_404(client):
client.post("/", data={"name": "Kofi", "message": "Akwaaba"})
assert b"Akwaaba" in client.get("/entries/1").data
missing = client.get("/entries/999")
assert missing.status_code == 404
assert b"No guestbook entry with that number." in missing.data
PY
uv run pytest -qDatabase code outside a request, such as the checks in test_signing_saves_an_entry, needs with app.app_context():, because db.session belongs to the app that is active. Inside a view, Flask provides that context for you.
Check it worked
pytest prints five dots and 5 passed. The guestbook you filled in by hand still has its two entries: the tests never touched instance/guestbook.sqlite.
uv run python -c "import sqlite3; con = sqlite3.connect('instance/guestbook.sqlite'); print(con.execute('SELECT count(*) FROM entries').fetchone()[0])"It prints 2.
Step 8 · Point the app at PostgreSQL in production
SQLite is a single file and suits development, tests and small sites with one server. For an app with many simultaneous writers, or one database shared by several servers, use PostgreSQL. The models, views and tests stay the same; only the address changes. Set up the server, a role and a database with install PostgreSQL 18 on Ubuntu 26.04, which creates appuser and appdb.
Add psycopg, the PostgreSQL driver SQLAlchemy uses for postgresql+psycopg:// addresses:
uv add "psycopg[binary]>=3.3,<3.4"Keep the password out of the address, your shell history and the code. psycopg uses libpq, which reads ~/.pgpass, so create that file private if it does not exist yet, then open it in your editor. If you followed the PostgreSQL tutorial it may already be there: if it has a line starting 127.0.0.1:5432:appdb:appuser:, there is nothing to add. Otherwise add one line in the form 127.0.0.1:5432:appdb:appuser:<your password> (replace <your password> with the one you set for appuser), and leave any other lines alone:
test -e ~/.pgpass || install -m 600 /dev/null ~/.pgpass
nano ~/.pgpassThen set the address in the environment of the process that runs the app, and create the tables in PostgreSQL:
export FLASK_SQLALCHEMY_DATABASE_URI='postgresql+psycopg://appuser@127.0.0.1:5432/appdb'
uv run flask --app guestbook init-dbOn a server, put the variable in the service's environment file, not in a shell profile. The tests still run on SQLite, because they pass their own configuration to the factory.
Check it worked
You can see the override working without PostgreSQL. Point the app at a different SQLite file through the same variable and print what the factory loaded:
FLASK_SQLALCHEMY_DATABASE_URI='sqlite:///staging.sqlite' uv run python -c "from guestbook import create_app; print(create_app().config['SQLALCHEMY_DATABASE_URI'])"It prints sqlite:///staging.sqlite. With PostgreSQL configured, init-db prints Tables ready in postgresql+psycopg://appuser@127.0.0.1:5432/appdb, and the guestbook starts empty in the new database.
Step 9 · Clean up
Stop the server with Ctrl+C in the second terminal.
Remove the demo project, including its database file. Python and uv stay installed. If you tried the PostgreSQL step, also remove the ~/.pgpass line if you added it only for this tutorial and drop the tables with DROP TABLE entries; in psql.
cd ~
rm -rf ~/flask-guestbook-demoCheck it worked
test ! -e ~/flask-guestbook-demo && echo "removed"It prints removed.
Next steps
- See exactly how bound parameters stop injected SQL, and what goes wrong without them: prevent SQL injection in Python and Node.
- Write more tests, with fixtures and parametrised cases: test Python code with pytest.
- Run the production database yourself: install PostgreSQL 18 on Ubuntu 26.04.
- Go back over routes, templates and the debug server: build your first web app with Flask 3.
Related tutorials
- Build your first web app with Flask 3You will build a small guestbook in Flask 3.1 on Python 3.15, with routes, Jinja templates that share a layout, a static stylesheet, a validated POST form, flash messages and a redirect after each post.
- How to Prevent SQL Injection in Python and Node.jsYou will write a login lookup that an attacker can break with one line of input, watch it fail, fix it with parameterised queries in both Python and Node.js, and learn the cases where parameters are not enough.
- How to Install PostgreSQL 18 on Ubuntu 26.04 and Create Your First DatabaseYou will install PostgreSQL 18 from the official PostgreSQL apt repository, create a database and a user for your app, and connect to it with a password.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials