Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
A small Flask blog with posts in a Python list: int converters and abort(404), request.args and request.form, a base layout, url_for and a blueprint, redirect after POST, flash, and a session cookie that breaks the moment you change it.
What you will learn
- Read values from the path, the query string and a form in a Flask view
- Share one layout with Jinja2 template inheritance and build every link with url_for
- Handle GET and POST in one view and redirect after a POST with flash messages
- Explain how Flask's signed session cookie works and why SECRET_KEY must come from the environment
Before you start
- Your first Flask app with uv
- HTML forms
Our first Flask app had one route and returned one line of text. Now it becomes a small blog with proper pages. The posts still sit in a plain Python list, two of them, so we can focus on the web part: what a request carries in (the path, the query string, the form) and what the app sends back (a page, a redirect or a cookie).
The project continues the uv project from Your first Flask app, with Flask 3.1.3.
The route table is the map of the app
uv run flask --app main routes
Endpoint Methods Rule
---------- --------- -----------------------
about.page GET /about
home GET /
login GET, POST /login
logout POST /logout
new GET, POST /new
post GET /post/<int:post_id>
static GET /static/<path:filename>
tag GET /tag/<name>
Each row has an endpoint (the name of the view), the methods it accepts and the rule (the URL pattern). Two rows weren't written with @app.route: static comes from Flask itself, and about.page comes from a blueprint. When a URL doesn't work, this table is the first thing to check.
Values in the URL
Here's the top of main.py and the post view:
import os
from flask import (Flask, abort, flash, redirect,
render_template, request, session,
url_for)
from about import bp as about_bp
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
app.register_blueprint(about_bp)
POSTS = [
{"id": 1, "title": "Packing a bag",
"body": "Roll clothes to save space."},
{"id": 2, "title": "A simple pasta",
"body": "Boil, drain, add sauce."},
]
@app.route("/post/<int:post_id>")
def post(post_id):
for p in POSTS:
if p["id"] == post_id:
return render_template("post.html", post=p)
abort(404)
@app.route("/tag/<name>")
def tag(name):
return render_template("tag.html", name=name)
Three requests to the post view behave differently, and the run shows all three:
| Request | What happens | Status |
|---|---|---|
/post/2 | the int converter turns "2" into 2, the view finds the pasta post | 200 |
/post/abc | not a number, so the rule doesn't match and the view never runs | 404 |
/post/99 | the rule matches, the loop finds nothing, abort(404) | 404 |
So a converter checks the type before your code runs, and abort handles the case your code finds. The tag view has no converter, so name is plain text. Even if someone puts an HTML tag in the URL, the page shows it as text, because Jinja escapes values for you.
The query string
@app.route("/")
def home():
q = request.args.get("q", "")
found = [p for p in POSTS
if q.lower() in p["title"].lower()]
return render_template("index.html",
posts=found, q=q)
The search form uses method="get", so searching for pasta asks for /?q=pasta. request.args.get("q", "") reads it, and the empty string is the default for a plain visit. The page shows A simple pasta, and Packing a bag drops out.
A good rule: the path says what a page is (a post id), and the query string holds options for that page (a search).
One layout for every page
Every page needs the same head, nav bar and messages. Write that once, in base.html, with gaps called blocks:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}Blog{% endblock %}</title>
<link rel="stylesheet"
href="{{ url_for('static',
filename='style.css') }}">
</head>
<body>
<nav>
<a href="{{ url_for('home') }}">Home</a>
<a href="{{ url_for('new') }}">New post</a>
<a href="{{ url_for('about.page') }}">About</a>
{% if session.user %}
<span>Signed in as {{ session.user }}</span>
<form method="post"
action="{{ url_for('logout') }}">
<button>Sign out</button>
</form>
{% else %}
<a href="{{ url_for('login') }}">Sign in</a>
{% endif %}
</nav>
{% for message in get_flashed_messages() %}
<p class="flash">{{ message }}</p>
{% endfor %}
{% block content %}{% endblock %}
</body>
</html>
index.html doesn't repeat any of that. It extends the base and fills the two blocks:
{% extends "base.html" %}
{% block title %}All posts{% endblock %}
{% block content %}
<h1>All posts</h1>
<form method="get" action="{{ url_for('home') }}">
<input name="q" value="{{ q }}">
<button>Search</button>
</form>
<ul>
{% for p in posts %}
<li>
<a href="{{ url_for('post',
post_id=p.id) }}">
{{ p.title }}</a>
</li>
{% else %}
<li>No posts found.</li>
{% endfor %}
</ul>
{% endblock %}
Change the nav once in base.html, and every page that extends it gets the change.
url_for: names, not paths
You don't type a friend's phone number each time you call. You tap their name, and if the number changes you update it once in your contacts. url_for works the same way. You give it the endpoint, and it gives you the URL. Change a rule later, and every link built with url_for follows it.
post_id=2 fills the variable in the rule. q='pasta' isn't in the rule, so it goes into the query string. The static endpoint gives the style sheet's URL, and the browser gets it back as text/css. _external=True gives the full address, which you need for a link that leaves the site, like one in an email.
A blueprint, named once
The about page sits in its own file, about.py:
from flask import Blueprint, render_template
bp = Blueprint("about", __name__)
@bp.route("/about")
def page():
return render_template("about.html")
A blueprint is a group of routes kept in a separate file. app.register_blueprint(about_bp) in main.py plugs it into the app, and the endpoint becomes the blueprint name, a dot and the view name: about.page. The finished blog splits every area into blueprints like this.
GET and POST in one view
@app.route("/new", methods=["GET", "POST"])
def new():
if request.method == "POST":
title = request.form["title"].strip()
if not title:
flash("Please give the post a title.")
return render_template("new.html")
item = {"id": len(POSTS) + 1, "title": title,
"body": request.form["body"].strip()}
POSTS.append(item)
flash("Post saved.")
return redirect(url_for("post",
post_id=item["id"]))
return render_template("new.html")
By default a route only answers GET. methods=["GET", "POST"] lets one function show the empty form (GET) and handle it (POST). request.form["title"] reads the input named title, and strip() takes the spaces off the ends.
Send a title that's only a space: after strip() it's empty, so the view flashes Please give the post a title. and shows the form again with status 200. get_flashed_messages() in the base layout prints that message above the content.
Redirect after a POST
A proper post, Weekend plans, becomes post 3. The view doesn't render a page. It returns a 302 with Location: /post/3, the browser follows it with a new GET, and the page comes back 200 with the Post saved. message on top. Open the page again and the message is gone: a flash shows once, then it's cleared. Because the last request was a GET, pressing refresh only reloads the post.
The same thinking applies to sign out. The logout route only allows POST:
@app.route("/logout", methods=["POST"])
def logout():
session.pop("user", None)
flash("You are signed out.")
return redirect(url_for("home"))
Just opening /logout is a GET, and Flask answers 405 Method Not Allowed with an Allow: POST, OPTIONS header. Opening a link should never change anything, so signing out is a button inside a small form.
The session: a note with a stamp
How does Flask remember who you are between requests? Think of a note with a stamp on it. Anyone can read the note, but if someone changes one word, the stamp no longer matches. Flask's session works like that: it writes your data into a cookie and signs it with the secret key.
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
session["user"] = request.form["username"]
flash("Welcome back.")
return redirect(url_for("home"))
return render_template("login.html")
Signing in with a test name gives a 302 to /, and the response sets a cookie called session. Its value is three parts joined with dots: the data, a timestamp and the signature. Decode the first part and it's plain JSON: the user name, plus the waiting Welcome back. message under _flashes (so flash messages travel in the session too). The cookie is HttpOnly with path /, so page scripts can't read it.
Anyone can read that data, so never put a password in the session.
In the lecture run, three things were tried:
- The next request carried the cookie, and the nav showed Signed in as with the welcome message. Ask again and you're still signed in, but the message is gone.
- The last three characters of the signature were changed by hand. Flask checked the signature, it didn't match, and it ignored the whole session: nobody signed in.
- Sign out popped
user, flashed You are signed out. and redirected home with a 302. The nav showed Sign in again.
The stamp doesn't hide your data. It only proves that the app wrote it.
The secret key comes from the environment
All of that rests on one line:
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
Set the variable in the terminal before you run the app. Never write the key itself into the code: code gets shared, and anyone with the key can sign their own cookie and act as any user.
Run the app without the variable, and get returns None. The moment login touches the session, Flask raises:
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
When you see that error, the fix isn't in your view. Set SECRET_KEY and run again.
Common mistakes
- Typing paths in templates. Use
url_for, so a changed rule doesn't break links. - Rendering a page after a successful POST. A refresh sends the form again. Redirect instead.
- A logout link that works with GET. Anything that changes state should need a POST.
- Secrets in the session. The data is signed, not encrypted.
- Forgetting the blueprint prefix in
url_for. It'sabout.page, notpage.
Quick recap
| Need | Flask tool |
|---|---|
| value in the path | <int:post_id>, then abort(404) if not found |
| search options | request.args.get("q", "") |
| form fields | request.form["title"] with methods=["GET", "POST"] |
| shared layout | {% extends "base.html" %} and blocks |
| links | url_for(endpoint, **values) |
| after a POST | flash(...) + redirect(url_for(...)) |
| remember the user | session, signed with SECRET_KEY from the environment |
Try it yourself
Add an edit page at /post/<int:post_id>/edit that takes GET and POST and redirects back to the post. Or prompt an AI tool to write it, and read every line it gives you. Next, the posts move into a real database in Flask-SQLAlchemy models and migrations.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
