Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 72 ยท Projects

Project: A Blog

Build a complete blog with Flask in three stages. Use an app factory, a blueprint, SQLAlchemy models, Jinja templates, CRUD views, pagination and tests.

It is time to put the pieces together. In this project you build a small but complete blog: a front page with pagination, a page for each post, and forms to create, edit and delete posts. Along the way you use almost everything from the previous chapters: an application factory, a blueprint, Flask-SQLAlchemy models, template inheritance, form handling, flash messages and custom error pages.

The blog grows in three stages, and every stage runs on its own:

  1. The data layer: the application factory, the Post model, slugs and pagination.
  2. The reading pages: a blueprint, a template folder and the list and detail views.
  3. The full app: create, edit and delete, validation, and an automated test suite.

As in the earlier lessons, there is no real server in the browser. We talk to the app through the test client and print what it returns. On your own computer you would put the pieces in separate files and start the app with flask run.

The plan

Before writing code, decide what the app must do and what parts it has.

URL Method What it does
/ GET Latest posts, three per page (?page=2)
/post/<slug> GET One post
/new GET, POST Form to write a post
/post/<slug>/edit GET, POST Form to change a post
/post/<slug>/delete POST Delete a post

A post has a title, a body and a slug: a URL-friendly name like my-first-post. Slugs make addresses readable and stable, so we create them once and keep them, even when the title is edited later.

On a real disk, the project looks like this:

TEXT
blog/
  __init__.py        create_app(), registers the db and the blueprint
  models.py          db and Post
  views.py           the "blog" blueprint
  templates/blog/    base.html, index.html, detail.html, form.html
tests/
  test_blog.py
flowchart TD
    F["create_app(config)"] --> D["db.init_app(app)"]
    F --> B["register blueprint 'blog'"]
    F --> E["404 error handler"]
    B --> V["views: index, detail,<br/>create, edit, delete"]
    V --> M["Post model"]
    V --> T["templates"]
    M --> D

The factory builds a fresh app each time: ideal for tests, which each get their own app and database.

Stage 1: the data layer

First, the db object, the Post model and a factory. The model lives apart from any app, and create_app() connects them. Remember from The Application Factory that the extension object exists at import time but only becomes active after db.init_app(app).

This stage also adds the two helpers that every blog needs. slugify() turns a title into a slug, and unique_slug() makes sure two posts with the same title don't collide. The last part seeds seven posts and reads them back with db.paginate(), Flask-SQLAlchemy's pagination helper.

Python Stage 1: factory, Post model and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the first line of output. The two "Hello, World!" posts got the slugs hello-world and hello-world-2: unique_slug() keeps adding a number until the slug is free. db.paginate() returned a Pagination object that knows the current page, the total number of pages and whether neighbouring pages exist, so the templates can draw the "Newer" and "Older" links without doing any arithmetic.

Stage 2: a blueprint and the reading pages

Now the web part. The views live in a blueprint called blog, so their endpoints are blog.index, blog.detail and so on, and the factory registers the blueprint with app.register_blueprint(blog). The page layout is a single base.html that the other templates extend.

Because there are no template files here, we serve the templates from a dictionary with a DictLoader, as in Jinja Templates Basics. In your real project, the keys would be the file paths under templates/.

Python Stage 2: blueprint, templates and read-only views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The home page is built from three parts: base.html (the frame), index.html (fills the content block) and the pagination object. Notice that all links come from url_for(); nothing in the templates repeats a URL. db.first_or_404() raises a 404 if there is no matching row, and db.paginate() does the same when the page number is past the end, so the visitor gets the custom 404 page in both cases.

Stage 3: create, edit, delete and tests

The last stage adds the write side. This is the pattern for every form in the app:

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: GET /new
    F-->>B: 200 empty form
    B->>F: POST /new (title, body)
    alt input is valid
        F->>F: save the post
        F-->>B: 302 redirect to the new post
        B->>F: GET /post/slug
        F-->>B: 200 post page + flash message
    else input is invalid
        F-->>B: 200 form again with errors and typed values
    end

Post/Redirect/Get: after a successful save the browser is redirected, so refreshing the page never re-submits the form.

Invalid input is not an error to crash on: it is a normal case. The form is shown again with the error messages and the values the visitor typed. Valid input is saved, a flash message is queued and the browser is redirected to the new page.

This version of the blog has no login, so anyone can edit anything. Project: Users and Login fixes that. The forms also have no CSRF protection yet; Web Security Essentials explains how to add it.

After the app comes a mini test suite in the style of Testing Flask Apps with pytest. Each test function receives a client for a brand-new app with its own empty in-memory database, which is exactly what a pytest fixture would give it. A short loop at the bottom plays the part of the test runner.

Python Stage 3: the complete blog with a test suite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every test starts from an empty database, so tests cannot interfere with each other. The assertions check what a visitor would see: status codes, redirect targets, text on the page and the number of rows saved. The last test confirms that Jinja's autoescaping keeps a post title containing a <script> tag from being treated as HTML; if you ever write |safe on user text, that test will start failing.

Where to go from here

You now have the skeleton of almost every Flask web app. Ideas to extend it:

  • Show a creation date and sort by it.
  • Add author and a one-to-many relationship, as in Relationships, then restrict editing to the author (Roles and Permissions).
  • Add comments and tags.
  • Render the body as Markdown (and sanitize it).
  • Switch to a file database and manage the schema with Migrations.
  • Deploy it with gunicorn and nginx.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the blog keep a post's slug unchanged when the title is edited?

    Changing a URL breaks every old link. Slugs are generated once and then treated as a stable identifier.
  2. 2. What is the purpose of redirecting after a successful POST?

    Post/Redirect/Get ends the POST with a redirect, so the browser's last request is a harmless GET.
  3. 3. In the blueprint named blog, which call builds the URL of the view function detail?

    A blueprint prefixes its endpoints with its own name, so the endpoint is blog.detail.
  4. 4. Why does each test in the suite call create_app() again?

    The application factory makes isolation cheap: every call returns a new app with its own configuration and database.
  5. 5. What should happen when a form is submitted with invalid data?

    Invalid input is a normal case. Re-rendering with errors and the typed values lets the visitor fix the problem.

Summary

  • An application factory plus a blueprint keeps the code organized and makes it easy to create isolated apps for tests.
  • db.paginate(), db.first_or_404() and db.session cover listing, looking up, saving and deleting posts.
  • Slugs give readable URLs; generate them once and make them unique.
  • Validate on the server, re-render the form with errors on failure, and use Post/Redirect/Get plus flash messages on success.
  • Test through the test client with a fresh app per test, and check visible behavior: status codes, redirects, page text and stored rows.

Next, build a different kind of application in Project: A Todo REST API.