Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

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:

RequestWhat happensStatus
/post/2the int converter turns "2" into 2, the view finds the pasta post200
/post/abcnot a number, so the rule doesn't match and the view never runs404
/post/99the 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.

url_for turns endpoint names into URLs: home gives slash, post with post_id 2 gives /post/2, home with q pasta gives /?q=pasta, static with filename style.css gives /static/style.css, about.page gives /about, and _external True gives http://localhost/. You write You get url_for reads the route table url_for('home') url_for('post', post_id=2) url_for('home', q='pasta') url_for('static', filename='style.css') url_for('about.page') url_for('home', _external=True) / /post/2 /?q=pasta /static/style.css /about http://localhost/
Real url_for results from the lecture run. A value that isn't in the rule, like q, goes into the query string.

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

The browser POSTs to /new. The view saves post 3 and answers 302 with Location /post/3. The browser sends a new GET to /post/3 and gets 200 with the Post saved message. A refresh repeats only the GET. Browser Flask app POST /new title=Weekend plans 302 Location: /post/3 GET /post/3 200 Weekend plans + "Post saved."
Post, redirect, get. The last request is a GET, so a refresh can't save the post twice.

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's about.page, not page.

Quick recap

NeedFlask tool
value in the path<int:post_id>, then abort(404) if not found
search optionsrequest.args.get("q", "")
form fieldsrequest.form["title"] with methods=["GET", "POST"]
shared layout{% extends "base.html" %} and blocks
linksurl_for(endpoint, **values)
after a POSTflash(...) + redirect(url_for(...))
remember the usersession, 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 42 of 48

Previous
Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
Next post
Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table

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.

On this page

  • The route table is the map of the app
  • Values in the URL
  • The query string
  • One layout for every page
  • url_for: names, not paths
  • A blueprint, named once
  • GET and POST in one view
  • Redirect after a POST
  • The session: a note with a stamp
  • The secret key comes from the environment
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.