Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 149 ยท Projects

Project: To-Do Web App

Build a to-do web app with Flask and SQLite. Render HTML templates, handle forms with POST and redirect, edit and delete tasks, escape user input, add CSRF protection and test it all.

The JSON API project taught your server to talk to other programs. This project teaches it to talk to people. You'll build a to-do web app: a real HTML page with a form to add tasks, buttons to tick them off, edit and delete them, and a filter for open and finished tasks. The data lives in a SQLite database, so it survives restarts.

Along the way you'll practice the things every server-rendered website needs: HTML templates with Jinja2, forms sent with POST, the post-redirect-get pattern, flash messages, database access with parameters, input validation, protection against XSS, SQL injection and CSRF, and tests that use the Flask test client. There are four stages.

How to run it here and at home

The editors on this page cannot open a network port, so they cannot serve pages to a browser. They don't need to: Flask's test client sends requests directly into the app and returns the HTML, which lets us print what a browser would receive. SQLite is part of Python, and the in-browser Python keeps its files in memory, so todo.db is created fresh on every run.

Flask is not part of the standard library, so each example starts by installing it with micropip (see Packages and pip). The first run downloads it and needs an internet connection. At home you would run pip install flask in a virtual environment, leave those two lines out, and start the real server with flask --app app run --debug. Stage 4 shows the file layout for that.

Stage 1: the database layer

Start with the data, before any web code. A task has an id, a title and a done flag. In SQLite that is one table. The most important habit in this stage is the placeholder ?: you never paste user text into SQL with an f-string, you pass values separately and let the database library handle them (see Databases with sqlite3).

Python Stage 1: a tasks table and four operations

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 third task looks like an attack, but because it went through a ? placeholder, SQLite treated it as ordinary text and stored it. done = 1 - done flips 0 to 1 and 1 to 0 in one statement, so the app never needs to read the old value first.

Stage 2: the first page, a form and post-redirect-get

Now put a web page in front of the data. A view function reads tasks and renders a template; a second view receives the form, saves the task and redirects back to the list.

That redirect is the post-redirect-get pattern, and it matters. If the server answered the POST with a page directly, pressing refresh would make the browser offer to submit the form again and create a duplicate task. Answering with a redirect makes the browser load the list with a harmless GET.

Python Stage 2: a list page and an add form

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.

Notice what the browser would do. It sends the form fields in the request body, Flask reads them from request.form, and the redirect response (status 302) has no page of its own, only a Location header. url_for('add_task') builds the form's address from the function name, so renaming a route can't break your links. And {{ task['title'] }} is automatically escaped by Jinja2, a fact stage 3 puts to the test.

Stage 3: the complete app

Now we add everything a real app needs. Here is the list of features and why each is there:

Feature Why
get_db() with Flask's g and a teardown function One connection per request, always closed, even after errors
Template inheritance (base.html) Shared page frame without copy and paste
toggle, delete and edit routes The rest of CRUD, one small route each
POST for every change Links (GET) must never change data, or a crawler could delete your tasks
clean_title() validation Trim, collapse spaces, reject blank or oversized titles
flash() messages Tell the user what happened after a redirect
A 404 for unknown ids Refuse politely instead of crashing
A CSRF token A hidden form field that a malicious site cannot guess (see below)
An optional ?show=open / ?show=done filter Query-string filtering with a fixed set of SQL strings

After defining the app, the script drives it with the test client the way a browser would, then runs four security checks. Read through it once; the explanations follow.

Python Stage 3: the complete to-do app

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.

Here is what to notice in that program.

Flask's g and the teardown hook. get_db() opens a connection the first time a request needs it and stores it in g, a per-request scratch space. @app.teardown_appcontext closes it when the request ends, success or failure. No view has to remember to close anything.

Only POST changes data. /1/delete accepts POST only. The last line of the script proves that a plain GET gets 405 Method Not Allowed. If deleting were a link, a search-engine crawler or a browser pre-fetching links would delete your tasks just by visiting them.

The filter uses fixed SQL. The show value from the URL decides which of three fixed strings to run. It is never pasted into the query. When a user value must appear in SQL, it goes through a ? placeholder.

Escaping stops XSS. The test saves the title <script>alert('xss')</script>. Because Jinja2 escapes < and > in .html templates, the page shows the text instead of running it. This is cross-site scripting (XSS) protection, and it only works if you never mark user text as |safe (see Python Security).

The placeholder stops SQL injection. A title containing '); DROP TABLE tasks; -- is stored as a harmless string, and the table survives.

The CSRF token stops forged forms. Cross-site request forgery is when another website makes your browser submit a form to your app while you're logged in there. The defense is a secret random token, stored in the session cookie and also embedded in every form. A before_request hook rejects any POST without the matching token, and the forged request in the script gets 400. This app has no logins, so the danger is smaller, but the pattern is the same one login-protected apps need. In a bigger project you'd use the Flask-WTF extension, which implements it for you.

The secret_key in the example is a placeholder. A real app reads it from an environment variable or a config file kept out of version control, because anyone who knows the key can forge session cookies. See the Flask configuration lesson and the Flask security lesson.

Stage 4: the layout for a real project

At home you'd split the single script into files. Flask finds templates in a folder called templates next to your app, so the three strings in TEMPLATES become three files:

TEXT
todo/
  app.py                 # the Flask code from stage 3, without the test-client part
  templates/
    base.html
    index.html
    edit.html
  static/
    style.css            # served at /static/style.css
  tests/
    test_app.py          # the checks from stage 3, as real unittest or pytest tests

Remove the DictLoader line (Flask then uses the folder), keep DB_PATH = "todo.db" as a real file path, and delete the code that removes the file at start-up. Then run:

TEXT
pip install flask
flask --app app run --debug

Open http://127.0.0.1:5000 in your browser. --debug reloads the server when you save a file and shows a helpful error page, but never use it on a public server. For real deployment you'd put the app behind a production server such as gunicorn instead of Flask's development server, as covered in the Flask deployment lesson.

The tests are the stage 3 checks turned into assertions. Because the test client needs no server, they run in a fraction of a second, and they catch regressions: if a later change accidentally makes /1/delete accept GET, a test fails.

Ideas to extend it

  1. Due dates and priorities. Add due and priority columns, order the list by them, and highlight overdue tasks with CSS.
  2. Users. Add registration and login with hashed passwords and a user_id column, so each person sees only their own tasks (see the Flask login lesson).
  3. Flask-SQLAlchemy. Replace the raw SQL with the ORM from SQLAlchemy once you have more than one table.
  4. Progressive enhancement. Add a few lines of JavaScript that submit the toggle button with fetch() so the page does not reload.
  5. An API. Add /api/tasks endpoints that return JSON, using the pattern from Project: JSON API with Flask, so a phone app could use the same data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does add_task end with redirect(url_for("index")) instead of rendering a page?

    This is the post-redirect-get pattern. The POST changes data and answers with a redirect, so the page the user lands on can be refreshed safely.
  2. 2. What stops the task title x'); DROP TABLE tasks; -- from damaging the database?

    Placeholders keep data and SQL separate, which prevents SQL injection. Jinja2 escaping protects the HTML output, which is a different problem.
  3. 3. Why do toggle and delete use POST instead of GET links?

    GET is meant to be safe: reading only. State changes belong in POST (or PUT and DELETE), which browsers and crawlers do not trigger by merely visiting a link.
  4. 4. What does the hidden CSRF token protect against?

    A malicious site cannot read or guess the token tied to the user's session, so a forged form is rejected.
  5. 5. What does @app.teardown_appcontext do in this app?

    Teardown functions run when the app context ends, even after an exception, so connections are never leaked.

Summary

  • A server-rendered app has views that read data and render templates, plus views that receive forms and change data.
  • Use post-redirect-get: answer every form submission with a redirect so refreshing never re-submits.
  • Only POST (never GET) may change data; unknown ids return 404.
  • Talk to SQLite with ? placeholders, open one connection per request through g, and close it in a teardown hook.
  • Jinja2 autoescaping prevents XSS; placeholders prevent SQL injection; a CSRF token in every form prevents forged submissions.
  • Validate input (strip, length limits) and give feedback with flash() messages.
  • Test the whole app, security rules included, with Flask's test client; at home split it into app.py, templates/, static/ and tests/.

Next: Data Structures and Algorithms, where the course turns to how data is organized and searched.