12.6. Flask and Persistence#
In this section, we’ll build a new Flask application: a small microblog where anyone can post short messages and see what others have posted.
To keep the example focused, we’ll intentionally avoid authentication to focus on persistence patterns (models, forms, database access, and request handling). The next section will introduce authentication and tie posts to users.
Our microblog will be a single page with:
a form to create a new post
a timeline that shows recent posts (newest first)
By the end of this section, you’ll know how to:
Configure Flask-SQLAlchemy
Use SQLite as a database
Define a database model
Create and query records
Validate input with WTForms
Apply Post-Redirect-Get (PRG) to prevent duplicate submissions
Write tests that use a temporary database
12.6.1. Project Layout and Dependencies#
We’ll use the same general structure as earlier sections, with a few new files for persistence.
flask-microblog-db/
├─ app.py # Flask app, config, database setup
├─ models.py # SQLAlchemy models (Post)
├─ forms.py # WTForms (PostForm)
├─ routes.py # Page handlers (compose + timeline)
├─ pytest.ini
├─ templates/
│ ├─ base.html
│ └─ index.html
├─ tests/
│ ├─ conftest.py
│ ├─ test_routes.py
│ ├─ test_posts.py
│ └─ test_validation.py
└─ static/
└─ styles.css
12.6.1.1. Install dependencies#
To add database support, we’ll use Flask-SQLAlchemy.
For forms and validation, we’ll continue using Flask-WTF.
pip install Flask Flask-SQLAlchemy Flask-WTF
To add a small command-line utility for initializing the database, we’ll use
Click (already installed as a Flask dependency).
12.6.2. Application Setup (app.py)#
As before, app.py creates the Flask app and loads routes.
In this app, it also configures the database and exposes a CLI command to initialize it.
SQLALCHEMY_DATABASE_URI tells Flask-SQLAlchemy how to connect to the database.
It’s commonly set from an environment variable so different environments can use different databases.
Examples:
sqlite:///app.dbpostgresql+psycopg://user:pass@localhost/dbname
Database URLs provides additional details and examples.
Models will use the single db object to interact with the database.
We’ve also added a command-line tool to initialize the database as necessary.
From a terminal window, use flask --app app init-db to execute it.
# app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask.cli import with_appcontext
import os, secrets, sys
import click
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", secrets.token_hex(16))
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get(
"DATABASE_URL", "sqlite:///app.db"
)
# Allow 'from app import app' even when run directly
sys.modules.setdefault("app", sys.modules[__name__])
db = SQLAlchemy(app)
# Import after app/db exist
import models # noqa: F401
import routes # noqa: F401
@app.cli.command("init-db")
@click.option("--drop", is_flag=True, help="Drop existing tables first.")
@click.option("--sample", is_flag=True, help="Insert sample rows after init.")
@with_appcontext
def init_db(drop, sample):
if drop:
db.drop_all()
db.create_all()
if sample:
from models import Post
db.session.add_all([
Post(body="Hello world"),
Post(body="Second post!")
])
db.session.commit()
click.echo("Database ready" + (" with sample data." if sample else "."))
if __name__ == "__main__":
# Dev convenience: create tables if missing
with app.app_context():
db.create_all()
app.run(debug=True)
Production note:
db.create_all()is convenient for demos, but real projects should use migrations (e.g., Flask-Migrate).
12.6.3. Models (models.py)#
The database model defines what data is stored and how it’s structured.
For this application, we’ll have a single Post class that tracks the microblogs.
Each post has:
a unique ID
a text body
a timestamp (when the post was created)
# models.py
from datetime import datetime, timezone
from app import db
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), index=True)
Notes:
Textallows unbounded contentnullable=Falseprevents empty rowsdatetime.utcnowis evaluated server-sideIndexing
timestampmakes sorting efficient
Related Documentation:
12.6.4. Forms (forms.py)#
We’ll use a FlaskForm to validate new posts.
# forms.py
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
class PostForm(FlaskForm):
body = TextAreaField(
"What's happening?",
validators=[DataRequired(), Length(max=280)]
)
submit = SubmitField("Post")
CSRF protection is enabled automatically via
FlaskFormand the app’sSECRET_KEY.
12.6.5. Routes (routes.py)#
The home page serves two roles:
GET /→ show the form and timelinePOST /→ create a new post, then redirect back (PRG)
# routes.py
from flask import render_template, redirect, url_for, flash
from app import app, db
from models import Post
from forms import PostForm
@app.route("/", methods=["GET", "POST"])
def index():
form = PostForm()
if form.validate_on_submit():
post = Post(body=form.body.data)
db.session.add(post)
db.session.commit() # Always commit after writes, or changes won’t persist
flash("Posted!")
return redirect(url_for("index")) # PRG
posts = (
Post.query
.order_by(Post.timestamp.desc())
.limit(50)
.all()
)
return render_template("index.html", form=form, posts=posts)
Key ideas:
validate_on_submit()ensures POST + valid dataPRG prevents duplicate submissions on refresh
Query sorts newest posts first
Mental Model: Routes create/query model objects through db.session, and templates render the results.
12.6.6. Templates#
The templates directory contains the base.html that provides the basic skeleton for the site along with index.html that provides the post form as well as the history timeline of previous posts.
In addition to providing the structure, the base template also provides a place to display flashed messages. The index template renders the form (including the CSRF token via hidden_tag) and the list of posts. We’ve kept markup minimal so the focus is on Flask mechanics. As an exercise, consider different
ways of presenting the posts.
12.6.6.1. templates/base.html#
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{% block title %}Microblog{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}" />
</head>
<body>
<header class="site-header">
<div class="container">
<h1><a href="/">Microblog</a></h1>
</div>
</header>
<main class="container">
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="card" role="status">
{% for m in messages %}<p>{{ m }}</p>{% endfor %}
</div>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</main>
<footer class="site-footer">
<div class="container">
<small>DB-only microblog</small>
</div>
</footer>
</body>
</html>
12.6.6.2. templates/index.html#
{% extends "base.html" %}
{% block title %}Home — Microblog{% endblock %}
{% block content %}
<section class="card">
<h2>Compose</h2>
<form method="post" class="stack">
{{ form.hidden_tag() }}
{{ form.body(rows=3, placeholder="What's happening?") }}
{% if form.body.errors %}
<small class="error">{{ form.body.errors[0] }}</small>
{% endif %}
{{ form.submit(class_="button") }}
</form>
</section>
<section class="card">
<h2>Recent Posts</h2>
{% if posts %}
<ul class="stack">
{% for p in posts %}
<li>
{{ p.body }}<br />
<small>{{ p.timestamp.strftime("%Y-%m-%d %H:%M") }} UTC</small>
</li>
{% endfor %}
</ul>
{% else %}
<p><em>No posts yet.</em></p>
{% endif %}
</section>
{% endblock %}
12.6.7. Static Files#
We’ve included a minimal CSS file to provide some style to the webpage without introducing a CSS framework or advanced concepts.
/* static/styles.css */
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; line-height: 1.5; color: #111827; background: #f7f7f9; }
.container { max-width: 760px; padding: 16px; margin: 0 auto; }
.site-header, .site-footer { background: #fff; border-bottom: 1px solid #e5e7eb; }
.site-footer { border-top: 1px solid #e5e7eb; border-bottom: none; }
.site-header h1 { margin: 0; font-size: 1.125rem; }
.site-header a { color: inherit; text-decoration: none; }
.card { background: #fff; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; box-shadow: 0 1px 2px rgba(0,0,0,0.06); margin-top: 16px; }
.stack { display: grid; gap: 12px; padding-left: 0; list-style: none; }
label span { display: block; font-size: 0.9rem; color: #4b5563; margin-bottom: 4px; }
input, textarea { width: 100%; padding: 8px 10px; border-radius: 6px; border: 1px solid #d1d5db; background: #fff; color: #111827; }
.button { display: inline-block; padding: 8px 12px; border-radius: 6px; border: 1px solid #2563eb; background: #2563eb; color: #fff; text-decoration: none; cursor: pointer; }
.button:hover { background: #1d4ed8; }
.error { color: #b91c1c; }
12.6.8. Run the App#
python app.py
# or
flask --app app run --debug
Visit http://127.0.0.1:5000/, post messages, refresh. The timeline persists as data is stored in SQLite.
12.6.9. Testing with a Database#
With a database in the mix, tests prove that requests actually create rows and that the timeline renders what’s in the DB. We’ll write fast, isolated tests using a temporary SQLite database, a Flask test client, and a few concise assertions.
Create a pytest.ini at the project root so pytest adds the current directory to PYTHONPATH:
[pytest]
pythonpath = .
12.6.9.1. Fixtures (tests/conftest.py)#
What this does:
Uses a temporary SQLite file
Reloads the app so it picks up test config
Creates tables for each test
Disables CSRF in tests
# tests/conftest.py
import pytest
import importlib, os, sys, pathlib
ROOT = pathlib.Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
@pytest.fixture()
def app(tmp_path, monkeypatch):
db_path = tmp_path / "test.db"
monkeypatch.setenv("DATABASE_URL", f"sqlite:///{db_path}")
for m in ["app", "routes", "models", "forms"]:
sys.modules.pop(m, None)
import app as app_module
app = app_module.app
db = app_module.db
app.config.update(TESTING=True, WTF_CSRF_ENABLED=False)
with app.app_context():
db.create_all()
yield app
with app.app_context():
db.session.remove()
@pytest.fixture()
def client(app):
return app.test_client()
Note: We use sys.modules.pop(...) to clear cached modules so the app re-imports with the test DATABASE_URL.
12.6.9.2. Route Smoke Tests#
Check that the home page renders and an empty DB shows the “No posts yet.” message. These fast checks catch missing templates or routing mistakes.
# tests/test_routes.py
def test_index_renders(client):
resp = client.get("/")
assert resp.status_code == 200
assert b"Compose" in resp.data
def test_empty_timeline(client):
resp = client.get("/")
assert resp.status_code == 200
assert b"No posts yet." in resp.data
12.6.9.3. Posting & PRG#
We want to ensure a valid POST creates a row, returns a redirect (PRG), and that the subsequent GET shows the post, newest first.
# tests/test_posts.py
from urllib.parse import urlparse
def test_post_redirects(client):
resp = client.post("/", data={"body": "hello"}, follow_redirects=False)
assert resp.status_code == 302
assert urlparse(resp.headers["Location"]).path == "/"
def test_latest_first(client):
client.post("/", data={"body": "first"})
client.post("/", data={"body": "second"})
page = client.get("/").data.decode()
assert page.find("second") < page.find("first")
12.6.9.4. Validation#
Invalid inputs should not create rows; the page should re-render with a visible error marker. We assert on CSS class presence rather than exact text (which can vary by version/locale).
# tests/test_validation.py
def test_empty_body_error(client):
resp = client.post("/", data={"body": ""})
assert resp.status_code == 200
assert b'class="error"' in resp.data
def test_body_too_long(client):
resp = client.post("/", data={"body": "x" * 500})
assert b'class="error"' in resp.data
12.6.9.5. Test Execution#
From the project root:
pytest -q
Optional coverage check:
pip install coverage
coverage run -m pytest -q
coverage report -m
12.6.10. Key Takeaways#
Persistence introduces state
Models define structure and constraints
PRG prevents duplicate writes
Tests should use temporary databases
SQLite is ideal for learning and local development
12.6.11. Exercises — Persistence with Flask-SQLAlchemy#
12.6.11.1. Exercise 1: Limit the Timeline to 10 Posts#
Right now, the timeline shows up to 50 posts. Update the route so it shows only the 10 most recent posts.
Tasks:
In
routes.py, change the query to use.limit(10)Verify the page still sorts newest-first
Post more than 10 messages and confirm only 10 display
Hint:
posts = Post.query.order_by(Post.timestamp.desc()).limit(10).all()
Concepts practiced:
Query ordering and limiting
Server-side pagination basics (without implementing pagination)
12.6.11.2. Exercise 2: Clear the Form After a Successful Post (PRG Check)#
After submitting a post, the app redirects back to /. Confirm that:
refreshing the page does not re-submit the form
the textarea appears empty after the redirect
Then add a short comment in routes.py explaining why PRG makes this behavior natural.
Tasks:
Submit a post
Refresh the page
Confirm you do not get duplicate posts
Add a short comment explaining what PRG prevents
Concepts practiced:
Post/Redirect/Get
Request lifecycle
Avoiding accidental duplicate writes
12.6.11.3. Exercise 3: Add a “Reset Timeline” Route#
Add a new route /reset that:
deletes all posts in the database
flashes a message like
"Timeline cleared"redirects back to
/
Requirements:
Use
db.session.query(Post).delete()or delete rows via SQLAlchemyCall
db.session.commit()Use
flash()andredirect(url_for("index"))
Concepts practiced:
Deleting records
Database transactions
Redirects and flash messages
12.6.11.4. Exercise 4: Show Remaining Character Count (280 Max)#
Your form enforces a max length of 280 characters. Update the template to show a simple character counter.
Goal: display something like:
“280 characters max”
or (optional challenge)
“X characters remaining”
Tasks:
Update
templates/index.htmlDisplay the max length value somewhere near the form
(Optional) show remaining characters using a small bit of JavaScript
Concepts practiced:
Validation constraints reflected in the UI
Template edits
Optional client-side enhancement (non-essential)