Home β€Ί Curriculum β€Ί Flask Web Development
Updated for Python 3.12+ Β· November 2026

🌢️ Flask Web Development
in Python

Learn Flask step by step: routes, URL variables, requests and responses, Jinja2 templates, forms, sessions, blueprints, the app factory, testing and deployment.

Intermediate 9 lessonsβ‰ˆ 63 min read by Glenn Pansensoy

What this lesson is about

Flask is a small web framework for Python. You write ordinary functions, tell Flask which URL each function should answer, and return a string, a template or a bit of JSON. Underneath it is a thin layer over two libraries, Werkzeug (which understands HTTP and WSGI) and Jinja2 (which fills in HTML templates). Because it ships with so few built-in decisions, Flask is popular for small sites, internal tools, prototypes and the HTTP front door of data or machine learning projects.

In real work you meet Flask whenever someone says "can you put a web page or an API in front of this script?". A report generator becomes a page with a download button, a model becomes a /predict endpoint, a form posts data into a database. Learning Flask also teaches you how the web really works: a request arrives, a function runs, a response goes back. Once that cycle is clear, every other framework, Django and FastAPI included, becomes easier to read.

A web server cannot run inside a browser tab, so the real Flask code on this page is marked as something to run on your computer, and I tested each of those examples with Flask's own test client. To keep the lesson hands-on anyway, I also built the key ideas from scratch in plain Python that does run here: a tiny @app.route router, a URL matcher with converters, a mock request cycle, string.Template rendering, a signed session cookie, a blueprint registry and even a WSGI call. Seeing the mechanism in thirty lines makes the real framework feel far less magical.

What you will learn

  • βœ“Create a Flask app and map URLs to view functions with @app.route
  • βœ“Capture parts of a URL with variables and converters such as <int:post_id>
  • βœ“Read query strings, form data and JSON from request, and build responses
  • βœ“Render HTML with Jinja2 templates, template inheritance, loops and escaping
  • βœ“Handle forms, flash messages and login state with the signed session
  • βœ“Organise a growing app with blueprints and the application factory pattern
  • βœ“Test routes with the test client and pytest, without starting a server
  • βœ“Register error handlers and prepare an app for deployment with a WSGI server

Why programmers should learn this

  • β˜…Flask turns a Python function into a web endpoint with one decorator, so you can share a script, a calculator or a model with people who will never open a terminal.
  • β˜…It teaches the request and response cycle with very little framework noise, which is the foundation for Django, FastAPI and every other web tool you will use later.
  • β˜…Its small core means you choose the database layer, form library and authentication yourself, so you learn how those pieces fit together instead of treating them as a black box.
  • β˜…Many companies keep internal dashboards, webhooks and small services written in Flask, so reading and maintaining it is a practical skill for backend and data roles.
  • β˜…The test client lets you check an entire web app in milliseconds with no browser and no running server, which makes habits like test-driven development easy to build.

Your first Flask app and what a route really is

A Flask application is an object. You create it with Flask(__name__), and the __name__ argument tells Flask where your module lives so it can find templates and static files later. Then you attach view functions to URLs with the @app.route decorator. When a browser asks for /about, Flask looks up the function registered for that path, calls it, and turns the return value into an HTTP response.

To run it, save the code as hello.py, install Flask in a virtual environment (see Virtual Environments and pip if that is new to you), and start the development server with the flask command. The --debug flag turns on the auto-reloader and the interactive debugger. Both are wonderful on your laptop and dangerous on a public server, because the debugger can execute code. Never leave debug mode on in production.

Before using the real framework any further, I want you to see that the decorator is not magic. A decorator that takes arguments is just a function returning a function, and @app.route("/") simply stores your view in a dictionary. The runnable block below builds a miniature version with a route method and a handle method that returns 404 for unknown paths and 405 when the path exists but the HTTP method does not match. Flask does the same bookkeeping with a much smarter matcher.

hello.py (run on your computer)run on your computer
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask"

@app.route("/about")
def about():
    return "<h1>About</h1><p>A tiny page.</p>"

Line by line

  1. 1Import the Flask class, the heart of every application.
  2. 3Create the application object. __name__ helps Flask locate resources relative to this file.
  3. 5-7Register home for the URL /. Whatever string it returns becomes the body of the response.
  4. 9-11A second route. Returning a string containing HTML is fine; Flask sends it with the text/html content type.
Start the development serverrun on your computer
python -m venv .venv
source .venv/bin/activate
pip install flask
flask --app hello run --debug

Line by line

  1. 1-2Create and activate a virtual environment so Flask is installed for this project only (on Windows use .venv\Scripts\activate).
  2. 3Install Flask and its dependencies.
  3. 4Run the app from hello.py. The server listens on port 5000 by default and reloads when you save a file.
A route decorator from scratch (runs in your browser)
class MiniApp:
    def __init__(self):
        self.routes = {}

    def route(self, path, methods=("GET",)):
        def decorator(func):
            for method in methods:
                self.routes[(method, path)] = func
            return func
        return decorator

    def handle(self, method, path):
        view = self.routes.get((method, path))
        if view is not None:
            return 200, view()
        if any(p == path for _, p in self.routes):
            return 405, "Method Not Allowed"
        return 404, "Not Found"


app = MiniApp()


@app.route("/")
def home():
    return "Hello from MiniApp"


@app.route("/save", methods=("POST",))
def save():
    return "Saved!"


print(app.handle("GET", "/"))
print(app.handle("GET", "/save"))
print(app.handle("POST", "/save"))
print(app.handle("GET", "/nope"))
print(sorted(app.routes))
Expected output
(200, 'Hello from MiniApp')
(405, 'Method Not Allowed')
(200, 'Saved!')
(404, 'Not Found')
[('GET', '/'), ('POST', '/save')]

Line by line

  1. 1-3The app keeps one dictionary that maps (method, path) pairs to view functions.
  2. 5-10route is a decorator factory: calling app.route(path) returns decorator, which records the function and hands it back unchanged.
  3. 12-18handle plays the role of the web server. A match runs the view; a known path with the wrong method gives 405; anything else gives 404.
  4. 21Create one app instance, just like Flask(__name__).
  5. 24-31Register two views. The second only accepts POST, mirroring methods=["POST"] in Flask.
  6. 34-38Try four requests, then list the registered keys. Notice that a GET to /save is a 405, not a 404.
πŸ’‘

Flask also has shortcuts @app.get("/x") and @app.post("/x") that mean the same as @app.route("/x", methods=["GET"]) and the POST equivalent. I use them in the rest of this page because they read clearly.

URL variables and converters

Real sites do not have one page per user or per article; they have a pattern. In Flask you put angle brackets in the rule, such as /user/<username>, and the matched text arrives as an argument with the same name. A converter in front of the name, like <int:post_id>, both restricts what matches and converts the value, so your function receives a real int and a request for /post/forty never reaches it at all (Flask answers 404).

The built-in converters I use most are string (the default, anything without a slash), int, float, path (like string but slashes are allowed, useful for file paths) and uuid. One security note that beginners miss: a value from the URL is user input. If you put it back into HTML, escape it, which is what markupsafe.escape does in the example. Jinja2 templates escape automatically, which is one reason to prefer them over building HTML in strings.

To see how a converter works, the runnable block turns a rule like /post/<int:post_id> into a regular expression with named groups, then applies a cast function to each captured piece. Flask and Django use much more refined machinery, but the idea of compiling a readable rule into a pattern is the same. Try changing the inputs and predict whether each one matches before you press Run.

Variables in routes (run on your computer)run on your computer
from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route("/user/<username>")
def profile(username):
    return f"Profile of {escape(username)}"

@app.route("/post/<int:post_id>")
def show_post(post_id):
    return f"Post number {post_id}"

@app.route("/files/<path:subpath>")
def files(subpath):
    return f"Looking for {escape(subpath)}"

@app.route("/links")
def links():
    return url_for("show_post", post_id=7)

Line by line

  1. 1-2url_for builds URLs from view names; escape makes text safe to place in HTML.
  2. 6-8The <username> part is captured and passed in as the username argument. It is escaped before going into the HTML.
  3. 10-12With the int converter, /post/42 gives post_id == 42 as an integer and /post/abc is a 404.
  4. 14-16The path converter accepts slashes, so /files/img/2024/a.png matches with subpath == "img/2024/a.png".
  5. 18-20url_for("show_post", post_id=7) returns /post/7. Building links with url_for means a changed rule never leaves broken links behind.
Compiling rules with converters (runs in your browser)
import re

CONVERTERS = {
    "str": (r"[^/]+", str),
    "int": (r"\d+", int),
    "path": (r".+", str),
}


def compile_rule(rule):
    casts = {}

    def replace(found):
        kind = found.group("conv") or "str"
        name = found.group("name")
        pattern, cast = CONVERTERS[kind]
        casts[name] = cast
        return f"(?P<{name}>{pattern})"

    regex = re.sub(r"<(?:(?P<conv>\w+):)?(?P<name>\w+)>", replace, rule)
    return re.compile(f"^{regex}$"), casts


def match(rule, url):
    regex, casts = compile_rule(rule)
    found = regex.match(url)
    if not found:
        return None
    return {key: casts[key](value) for key, value in found.groupdict().items()}


print(match("/user/<username>", "/user/ana"))
print(match("/post/<int:post_id>", "/post/42"))
print(match("/post/<int:post_id>", "/post/forty"))
print(match("/files/<path:subpath>", "/files/img/2024/a.png"))
print(match("/<int:year>/<int:month>", "/2025/11"))
Expected output
{'username': 'ana'}
{'post_id': 42}
None
{'subpath': 'img/2024/a.png'}
{'year': 2025, 'month': 11}

Line by line

  1. 3-7Each converter pairs a regular-expression fragment with a function that converts the matched text.
  2. 10-22compile_rule rewrites every <converter:name> in the rule into a named regex group and remembers which cast belongs to which name.
  3. 17The substitution regex reads an optional converter: prefix followed by the variable name.
  4. 25-30match applies the compiled pattern to a URL. A failed match returns None; a successful one returns a dictionary of converted values.
  5. 33-37Five trial matches. The int converter rejects forty because \d+ only accepts digits.
ℹ️

A trailing slash matters in Flask. A rule written /projects/ redirects a request for /projects to the slash version, while a rule written /about without the slash returns 404 for /about/. Pick one style and stay consistent.

The request and the response

Inside a view you reach the incoming request through the request object, which Flask makes available as a proxy for the current request. Query-string values such as ?q=flask&page=2 live in request.args; submitted HTML form fields live in request.form; a JSON body is read with request.get_json(); and headers and cookies are in request.headers and request.cookies. Use .get() with a default instead of square brackets so a missing key does not crash the view with a 400 error.

What your view returns becomes the response. A string is sent as HTML with status 200. A dictionary, or the result of jsonify, becomes a JSON response with the right content type. A tuple lets you add a status code (and optionally headers), like return jsonify(error="..."), 400. When you need full control, such as setting a cookie, call make_response and change the object before returning it. redirect(url_for(...)) sends the browser to another page, and it is the right way to finish a successful form post.

HTTP methods carry meaning. GET should only read, so it is safe to repeat and cache. POST creates or changes something. Following that convention keeps your app friendly to browsers, search crawlers and API clients. The runnable block that follows is a mock of the whole cycle: a Request dataclass, a Response dataclass, a make_response function that normalises whatever a view returns, and a small dispatcher that logs both directions. It is only about sixty lines, yet it shows why a view can return a dict, a tuple or a string and still work.

Request and response helpers (run on your computer)run on your computer
from flask import Flask, request, jsonify, redirect, url_for, make_response

app = Flask(__name__)

@app.get("/search")
def search():
    term = request.args.get("q", "").strip()
    page = request.args.get("page", 1, type=int)
    return jsonify(term=term, page=page)

@app.post("/api/items")
def create_item():
    data = request.get_json(silent=True) or {}
    if "name" not in data:
        return jsonify(error="name is required"), 400
    return jsonify(id=1, name=data["name"]), 201

@app.get("/old-search")
def old_search():
    return redirect(url_for("search"))

@app.get("/theme")
def theme():
    resp = make_response("theme saved")
    resp.set_cookie("theme", "dark", httponly=True, samesite="Lax")
    return resp

Line by line

  1. 1Import the request proxy and the common response helpers.
  2. 5-9Read optional query parameters. type=int converts page and falls back to the default if the value is not a number.
  3. 11-16Parse a JSON body. silent=True returns None instead of raising when the body is missing or invalid, so we can answer with our own 400 message. The tuple adds a status code.
  4. 18-20Redirect to another view by name. The browser then makes a new GET request to /search.
  5. 22-26Build a response object by hand so a cookie can be attached. httponly hides it from JavaScript and samesite limits cross-site sending.
A mock request and response cycle (runs in your browser)
import json
from dataclasses import dataclass, field
from urllib.parse import urlsplit, parse_qs


@dataclass
class Request:
    method: str
    url: str
    body: str = ""

    @property
    def path(self):
        return urlsplit(self.url).path

    @property
    def args(self):
        return {k: v[0] for k, v in parse_qs(urlsplit(self.url).query).items()}

    def get_json(self):
        return json.loads(self.body) if self.body else None


@dataclass
class Response:
    body: str = ""
    status: int = 200
    headers: dict = field(default_factory=lambda: {"Content-Type": "text/html"})


def make_response(rv):
    if isinstance(rv, Response):
        return rv
    if isinstance(rv, tuple):
        body, status = rv
        resp = make_response(body)
        resp.status = status
        return resp
    if isinstance(rv, dict):
        return Response(json.dumps(rv, sort_keys=True),
                        headers={"Content-Type": "application/json"})
    return Response(str(rv))


def search(req):
    return {"term": req.args.get("q", ""), "page": int(req.args.get("page", 1))}


def create(req):
    data = req.get_json() or {}
    if "name" not in data:
        return {"error": "name is required"}, 400
    return {"id": 1, "name": data["name"]}, 201


def home(req):
    return "<h1>Welcome</h1>"


VIEWS = {("GET", "/search"): search, ("POST", "/items"): create, ("GET", "/"): home}


def cycle(req):
    print("-->", req.method, req.url)
    resp = make_response(VIEWS[(req.method, req.path)](req))
    print("<--", resp.status, resp.headers["Content-Type"], resp.body)


cycle(Request("GET", "/"))
cycle(Request("GET", "/search?q=flask&page=2"))
cycle(Request("POST", "/items", body='{"name": "lamp"}'))
cycle(Request("POST", "/items", body="{}"))
Expected output
--> GET /
<-- 200 text/html <h1>Welcome</h1>
--> GET /search?q=flask&page=2
<-- 200 application/json {"page": 2, "term": "flask"}
--> POST /items
<-- 201 application/json {"id": 1, "name": "lamp"}
--> POST /items
<-- 400 application/json {"error": "name is required"}

Line by line

  1. 6-20Request bundles what arrived: method, URL and body. path and args are computed from the URL, like request.path and request.args in Flask.
  2. 23-26Response holds a body, a status code and headers, with HTML as the default content type.
  3. 29-41make_response is the normaliser: a ready Response passes through, a tuple sets the status, a dict becomes JSON, and anything else becomes text.
  4. 44-52Three views written exactly as you would write Flask views: they return a dict, a tuple, or a string.
  5. 55-61The dispatcher looks up the view, normalises the result and prints both sides of the exchange.
  6. 64-67Four mock requests: an HTML page, a query string, a successful JSON POST and a failing one.

Jinja2 templates

Building HTML inside Python strings gets painful fast, and it is unsafe if you forget to escape user text. Flask therefore uses Jinja2 templates. You keep HTML in a templates/ folder next to your code and call render_template("name.html", key=value). Inside the template, {{ value }} prints a variable, {% for %} and {% if %} add logic, and {# ... #} is a comment. For .html files Flask turns on autoescaping, so a title like <script> is printed as harmless text instead of being run by the browser.

The feature that makes templates scale is inheritance. A base.html defines the page skeleton, navigation and footer, with {% block content %}{% endblock %} holes. Each page then says {% extends "base.html" %} and fills in only the blocks it needs. Filters transform values on the way out, for example {{ name|title }} or {{ items|length }}, and url_for('static', filename='site.css') gives a correct link to your CSS regardless of where the app is mounted.

Keep templates for presentation and keep decisions in Python. If a template needs a complicated condition, compute a simple value in the view and pass it in. The browser-runnable block uses the standard library's string.Template to show the underlying idea of filling placeholders in text, and html.escape to show what autoescaping does for you. string.Template has no loops or inheritance, so I build the list rows in Python. It is a teaching model, not a replacement for Jinja2.

templates/base.htmlrun on your computer
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{% block title %}My Notes{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='site.css') }}">
</head>
<body>
  <nav><a href="{{ url_for('notes') }}">Notes</a></nav>
  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>

Line by line

  1. 1-3A normal HTML skeleton. Nothing special yet.
  2. 5{% block title %} defines a hole that child templates may override; the text inside is the default.
  3. 6url_for('static', ...) generates the URL of a file inside your static/ folder.
  4. 9Links are built from view names, so they survive route changes.
  5. 11The main hole that every page fills with its own content.
templates/notes.html and its viewrun on your computer
{% extends "base.html" %}
{% block title %}Notes for {{ user }}{% endblock %}
{% block content %}
  <h1>{{ user|title }}'s notes</h1>
  {% if items %}
    <ul>
    {% for item in items %}
      <li class="{{ 'done' if item.done else 'open' }}">{{ loop.index }}. {{ item.title }}</li>
    {% endfor %}
    </ul>
  {% else %}
    <p>No notes yet.</p>
  {% endif %}
{% endblock %}

Line by line

  1. 1Inherit the skeleton from base.html.
  2. 2Override the title block, using a variable from the view.
  3. 4Print a variable and pass it through the title filter.
  4. 5-13Branch with if, loop with for. loop.index counts from 1. Output is escaped automatically, so <b> in a title shows as text.
The view that renders it (run on your computer)run on your computer
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/notes")
def notes():
    items = [
        {"title": "Buy rice", "done": False},
        {"title": "Write the lesson <draft>", "done": True},
    ]
    return render_template("notes.html", items=items, user="ana")

Line by line

  1. 1-3Import render_template and create the app.
  2. 6-9Build plain Python data. Templates can read dictionary keys with dot syntax, so item.title works.
  3. 10Render the template, passing keyword arguments that become template variables.
Filling placeholders and escaping (runs in your browser)
from string import Template
import html

page = Template("<h1>$title</h1>\n<ul>\n$items</ul>")
row = Template('  <li class="$cls">$text</li>\n')

notes = [("Buy rice", False), ("Write lesson <3", True), ('Say "hi" & wave', False)]
rows = "".join(
    row.substitute(cls="done" if done else "open", text=html.escape(text))
    for text, done in notes
)
print(page.substitute(title="My notes", items=rows))

print(Template("Hello $name, you have $count notes").safe_substitute(name="Ana"))
try:
    Template("Hello $name").substitute({})
except KeyError as err:
    print("missing placeholder:", err)
Expected output
<h1>My notes</h1>
<ul>
  <li class="open">Buy rice</li>
  <li class="done">Write lesson &lt;3</li>
  <li class="open">Say &quot;hi&quot; &amp; wave</li>
</ul>
Hello Ana, you have $count notes
missing placeholder: 'name'

Line by line

  1. 1-2string.Template uses $name placeholders; html provides escape.
  2. 4-5One template for the whole page and one for each list row.
  3. 7Sample data, including characters that are special in HTML.
  4. 8-11Build the rows in Python. html.escape converts <, >, & and quotes into safe entities, which is what Jinja2 autoescaping does for you.
  5. 12Substitute the finished rows into the page and print the HTML.
  6. 14safe_substitute leaves unknown placeholders alone instead of failing.
  7. 15-18substitute is strict: a missing value raises KeyError. Jinja2, by contrast, prints an empty string for undefined variables unless you configure it otherwise.
⚠️

Never mark user text as safe (|safe or Markup) unless you generated it yourself. Doing so switches off the protection that stops cross-site scripting attacks.

Forms, flash messages and sessions

A form is an HTML <form method="post"> whose fields arrive in request.form. The usual pattern is one view that handles both methods: on GET it shows the empty form, on POST it validates the input, and if everything is fine it saves and redirects (the post/redirect/get pattern) so that refreshing the page does not submit the form twice. If something is wrong, it re-renders the form with an error message and the values the person already typed. Always validate on the server, because browser-side checks can be bypassed.

To remember who is logged in you need state between requests, because HTTP itself forgets everything. Flask's session is a dictionary whose contents are stored in a signed cookie. The signature, made with your SECRET_KEY, lets Flask detect tampering, but the cookie is signed and not encrypted, so anything you put in it can be read by the user. Store a user id, never a password or a secret. A weak or leaked SECRET_KEY lets attackers forge sessions, so load it from an environment variable in production.

Passwords must never be stored or compared as plain text. Werkzeug (installed with Flask) offers generate_password_hash and check_password_hash so you only keep a salted hash. flash() queues a one-time message in the session that the next rendered page can show with get_flashed_messages(). After the real Flask example, I rebuild the signed cookie by hand with hmac, so you can see exactly why tampering is caught while reading is still possible, and I show server-side form validation with the standard library.

Login with form, session and flash (run on your computer)run on your computer
import os
from flask import (Flask, render_template, request, redirect,
                   url_for, flash, session)
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "dev-only-change-me")

USERS = {"ana": generate_password_hash("correct horse")}

@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        username = request.form.get("username", "").strip()
        password = request.form.get("password", "")
        stored = USERS.get(username)
        if stored and check_password_hash(stored, password):
            session["user"] = username
            flash("Welcome back!")
            return redirect(url_for("dashboard"))
        error = "Invalid username or password"
    return render_template("login.html", error=error)

@app.get("/dashboard")
def dashboard():
    user = session.get("user")
    if user is None:
        return redirect(url_for("login"))
    return render_template("dashboard.html", user=user)

@app.post("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))

Line by line

  1. 1-4Imports, including Werkzeug's password helpers.
  2. 6-7The secret key signs the session cookie. Read it from the environment so it never lives in your repository.
  3. 9A stand-in user table that holds a hash of the password, never the password itself. Use a real database in a real app.
  4. 11-14One view handles both methods. error starts empty for a fresh GET.
  5. 15-17Read submitted fields with .get() and sensible defaults.
  6. 18-22If the user exists and the hash matches, store the username in the session, queue a flash message and redirect (post/redirect/get).
  7. 23-24Otherwise show the form again with one generic message. Saying only "invalid username or password" avoids revealing which one was wrong.
  8. 26-31A protected page: no user in the session means a redirect to the login form.
  9. 33-36Logging out clears the session. It is a POST because it changes state.
templates/login.htmlrun on your computer
{% extends "base.html" %}
{% block content %}
  <h1>Log in</h1>
  {% for message in get_flashed_messages() %}
    <p class="flash">{{ message }}</p>
  {% endfor %}
  {% if error %}<p class="error">{{ error }}</p>{% endif %}
  <form method="post">
    <label>Username <input name="username" required></label>
    <label>Password <input name="password" type="password" required></label>
    <button type="submit">Log in</button>
  </form>
{% endblock %}

Line by line

  1. 4-6Show any queued flash messages once; they are removed after being read.
  2. 7Show the error, if the view passed one.
  3. 8-12A plain POST form. With no action attribute it submits to the same URL. Real apps should add a CSRF token, for example with the Flask-WTF extension.
A signed cookie from scratch (runs in your browser)
import base64
import hashlib
import hmac
import json

SECRET = b"dev-only-secret"


def mac_for(payload):
    return hmac.new(SECRET, payload.encode(), hashlib.sha256).hexdigest()


def sign(data):
    raw = json.dumps(data, sort_keys=True).encode()
    payload = base64.urlsafe_b64encode(raw).decode()
    return f"{payload}.{mac_for(payload)}"


def load(cookie):
    payload, _, mac = cookie.rpartition(".")
    if not hmac.compare_digest(mac, mac_for(payload)):
        return None
    return json.loads(base64.urlsafe_b64decode(payload))


cookie = sign({"user": "ana", "admin": False})
print("loads fine:", load(cookie))

payload, mac = cookie.split(".")
print("anyone can read it:", base64.urlsafe_b64decode(payload).decode())

forged = base64.urlsafe_b64encode(b'{"admin": true, "user": "ana"}').decode()
print("forged payload, old signature:", load(forged + "." + mac))
print("same payload, wrong key:", load(forged + "." + "0" * 64))
Expected output
loads fine: {'admin': False, 'user': 'ana'}
anyone can read it: {"admin": false, "user": "ana"}
forged payload, old signature: None
same payload, wrong key: None

Line by line

  1. 1-6Only the standard library is needed. The secret is a fixed example here; a real key is long, random and private.
  2. 9-10The signature is an HMAC-SHA256 of the payload, which only someone with the secret can compute.
  3. 13-16sign serialises the data, encodes it so it is safe in a cookie, and appends the signature after a dot.
  4. 19-23load recomputes the signature and compares in constant time. A mismatch means the cookie was changed, so we return None.
  5. 26-27A valid cookie round-trips.
  6. 29-30The payload is only base64, not encrypted: anyone can decode and read it. That is why secrets do not belong in a Flask session.
  7. 32-34An attacker flips admin to true but cannot produce a matching signature, so both forgery attempts are rejected.
Server-side form validation (runs in your browser)
from urllib.parse import parse_qs


def parse_form(body):
    return {key: values[0] for key, values in parse_qs(body).items()}


def validate_signup(form):
    errors = {}
    name = form.get("name", "").strip()
    age = form.get("age", "")
    if not name:
        errors["name"] = "Name is required."
    if not age.isdigit() or not 13 <= int(age) <= 120:
        errors["age"] = "Age must be a whole number from 13 to 120."
    return errors


good = parse_form("name=Ana&age=29")
bad = parse_form("name=+&age=abc")
print(good, validate_signup(good))
print(bad, validate_signup(bad))
Expected output
{'name': 'Ana', 'age': '29'} {}
{'name': ' ', 'age': 'abc'} {'name': 'Name is required.', 'age': 'Age must be a whole number from 13 to 120.'}

Line by line

  1. 1-5A form post body looks like a query string, name=Ana&age=29. parse_qs splits it, and we keep the first value of each field, like request.form.
  2. 8-16Validation returns a dictionary of field errors; an empty dictionary means the form is valid. Strings are checked before converting, so int() never crashes.
  3. 19-22A good and a bad submission. In Flask the error dictionary would be passed back to the template so the page can show each message next to its field.

Blueprints and the application factory

One file with fifty routes is hard to read. A blueprint is a bundle of routes, templates and handlers that you define separately and plug into the app later. A blog blueprint might own everything under /blog, an API blueprint everything under /api. You create it with Blueprint("blog", __name__, url_prefix="/blog"), decorate views with @bp.route, and register it with app.register_blueprint(bp). Endpoint names get the blueprint name as a prefix, so you write url_for("blog.detail", post_id=1).

The second structure idea is the application factory: instead of creating app at the top of a module, you define a function create_app(config=None) that builds and returns a configured app. That solves real problems. Tests can build a fresh app with test settings for every test, you can run two differently configured apps in one process, and circular imports disappear because extensions are attached inside the function. The flask run command finds a function called create_app automatically.

The first block below is a small package layout I tested with the test client. The runnable block reproduces the concept with plain classes: a Blueprint that collects rules, an App that copies them in under a prefix, and a factory that returns two independent apps with different configuration. Notice that the blueprint objects are created once at import time, while each app instance is created on demand.

Project layoutrun on your computer
notes_app/
    __init__.py        # contains create_app()
    blog.py            # the blog blueprint
    api.py             # the JSON API blueprint
    templates/
        base.html
        blog/
            index.html
tests/
    test_app.py
wsgi.py

Line by line

  1. 1-3The package folder; __init__.py holds the factory.
  2. 4-5One module per blueprint keeps related routes together.
  3. 6-9Templates live in a folder named after the blueprint to avoid clashing names.
  4. 10-11Tests and a small wsgi.py entry point for production servers sit outside the package.
notes_app/__init__.py and blog.py (run on your computer)run on your computer
# notes_app/__init__.py
from flask import Flask


def create_app(config=None):
    app = Flask(__name__)
    app.config.from_mapping(SECRET_KEY="dev", ITEMS_PER_PAGE=10)
    if config:
        app.config.update(config)

    from . import blog, api
    app.register_blueprint(blog.bp)
    app.register_blueprint(api.bp)
    return app


# notes_app/blog.py
from flask import Blueprint, abort, jsonify

bp = Blueprint("blog", __name__, url_prefix="/blog")

POSTS = {1: {"title": "Hello"}, 2: {"title": "Second post"}}


@bp.get("/")
def index():
    return jsonify(sorted(POSTS))


@bp.get("/<int:post_id>")
def detail(post_id):
    post = POSTS.get(post_id)
    if post is None:
        abort(404)
    return jsonify(post)


# notes_app/api.py
from flask import Blueprint, current_app, jsonify

bp = Blueprint("api", __name__, url_prefix="/api")


@bp.get("/config")
def show_config():
    return jsonify(per_page=current_app.config["ITEMS_PER_PAGE"])

Line by line

  1. 1-12The factory builds the app, loads defaults, lets the caller override them, then registers each blueprint. Importing the blueprints inside the function avoids circular imports.
  2. 16-20A blueprint with a URL prefix. Its routes become /blog/ and /blog/<id>.
  3. 23-25index returns the sorted post ids as JSON.
  4. 28-33abort(404) stops the view and triggers Flask's not-found handling.
  5. 37-44Inside a view, current_app points to the app handling this request, which is how blueprints read configuration without importing the app.
Blueprints and a factory from scratch (runs in your browser)
class Blueprint:
    def __init__(self, name, prefix=""):
        self.name = name
        self.prefix = prefix
        self.rules = []

    def get(self, path):
        def decorator(func):
            self.rules.append((path, func))
            return func
        return decorator


class App:
    def __init__(self, config=None):
        self.config = {"DEBUG": False, "GREETING": "Hello"}
        self.config.update(config or {})
        self.routes = {}

    def register_blueprint(self, bp):
        for path, func in bp.rules:
            self.routes[bp.prefix + path] = func

    def get(self, path):
        view = self.routes.get(path)
        return view(self) if view else "404 Not Found"


blog = Blueprint("blog", "/blog")
api = Blueprint("api", "/api")


@blog.get("/")
def blog_index(app):
    return f"{app.config['GREETING']} from the blog"


@api.get("/status")
def api_status(app):
    return {"debug": app.config["DEBUG"]}


def create_app(config=None):
    app = App(config)
    app.register_blueprint(blog)
    app.register_blueprint(api)
    return app


production = create_app()
testing = create_app({"DEBUG": True, "GREETING": "Test"})

print(sorted(production.routes))
print(production.get("/blog/"))
print(testing.get("/blog/"))
print(production.get("/api/status"), testing.get("/api/status"))
print(production.get("/missing"))
Expected output
['/api/status', '/blog/']
Hello from the blog
Test from the blog
{'debug': False} {'debug': True}
404 Not Found

Line by line

  1. 1-12A blueprint just collects (path, view) pairs and remembers a URL prefix. Nothing runs until an app registers it.
  2. 15-28The app has its own config dictionary and route table. Registering a blueprint copies each rule in with the prefix added.
  3. 31-32Two blueprints are created once, at import time.
  4. 35-42Views receive the app so they can read configuration, standing in for current_app in Flask.
  5. 45-49The factory builds a new app each time it is called.
  6. 52-53Two separate apps from the same blueprints: one with defaults, one for testing.
  7. 55-59Each app answers according to its own config, which is exactly why factories make tests easy.

Testing with the test client

A web app is easy to test because a request is just data in and data out. Flask gives you app.test_client(), an object that sends fake requests straight into your app and returns real response objects, with no network and no server. You call client.get("/blog/1") or client.post("/login", data={...}) and then assert on response.status_code, response.get_json() or response.data. A full test suite for a small app runs in well under a second.

With the application factory, pytest fixtures become short and clear. A app fixture calls create_app({"TESTING": True}), and a client fixture turns it into a client. Each test then gets a fresh application. Set follow_redirects=True when you want the final page after a redirect, and use with client.session_transaction() as sess: to prepare a logged-in session without going through the login form. Testing is a skill in its own right, and Testing with pytest goes deeper into fixtures and parametrisation.

The runnable block applies the same pattern to a tiny home-made app using unittest from the standard library. I run the suite with a custom runner that writes to a buffer, so the page prints only the facts: how many tests ran and whether they passed. Writing small tests like these while you learn is the habit that will save you most often when the code grows.

tests/test_app.py (run on your computer with pytest)run on your computer
import pytest
from notes_app import create_app


@pytest.fixture
def app():
    return create_app({"TESTING": True, "ITEMS_PER_PAGE": 3})


@pytest.fixture
def client(app):
    return app.test_client()


def test_blog_index_lists_ids(client):
    response = client.get("/blog/")
    assert response.status_code == 200
    assert response.get_json() == [1, 2]


def test_detail_returns_post(client):
    response = client.get("/blog/2")
    assert response.get_json() == {"title": "Second post"}


def test_unknown_post_is_404(client):
    assert client.get("/blog/99").status_code == 404


def test_config_override_is_visible(client):
    assert client.get("/api/config").get_json() == {"per_page": 3}

Line by line

  1. 1-2Import pytest and the factory, not a global app.
  2. 5-7The app fixture builds a new application with test settings for every test.
  3. 10-12The client fixture wraps it in the test client.
  4. 15-18Request a URL and check the status code and the parsed JSON body.
  5. 21-23Check the value for a specific post.
  6. 26-27A missing post should give 404, which abort(404) produces.
  7. 30-31Proof that the config override reached the blueprint through current_app.
Testing a tiny app with unittest (runs in your browser)
import io
import unittest


class TinyApp:
    def __init__(self):
        self.routes = {"/": "home", "/hello": "hi"}

    def test_client(self):
        return TinyClient(self)


class TinyClient:
    def __init__(self, app):
        self.app = app

    def get(self, path):
        body = self.app.routes.get(path)
        return {"status_code": 200 if body else 404, "data": body}


class TinyAppTests(unittest.TestCase):
    def setUp(self):
        self.client = TinyApp().test_client()

    def test_home(self):
        response = self.client.get("/")
        self.assertEqual(response["status_code"], 200)
        self.assertEqual(response["data"], "home")

    def test_missing_is_404(self):
        self.assertEqual(self.client.get("/nope")["status_code"], 404)

    def test_hello_body(self):
        self.assertEqual(self.client.get("/hello")["data"], "hi")


suite = unittest.defaultTestLoader.loadTestsFromTestCase(TinyAppTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("tests run:", result.testsRun)
print("all passed:", result.wasSuccessful())
print("failures:", len(result.failures), "errors:", len(result.errors))
Expected output
tests run: 3
all passed: True
failures: 0 errors: 0

Line by line

  1. 1-2unittest ships with Python, and io lets us capture the runner's chatter.
  2. 5-9A deliberately tiny app with a test_client() method, mimicking Flask.
  3. 12-18The client answers a GET without any network and returns a status code and data.
  4. 21-23setUp runs before every test, so each test starts with a fresh app and client.
  5. 25-33Three tests using assertEqual, the same style as asserting on a Flask response.
  6. 36-39Run the suite into an in-memory stream and print the counts, which are deterministic.

Error handlers

Things go wrong: a user asks for a page that does not exist, a form field is invalid, or your own code raises an exception. Flask converts HTTP errors into responses through error handlers. abort(404) raises an HTTPException; if you registered a function with @app.errorhandler(404), Flask calls it and uses what it returns, otherwise the plain default page is shown. The handler receives the exception object and must return a response, usually together with the status code.

You can register handlers for status codes or for exception classes, including your own. A common design is a custom ValidationError raised deep in the code and turned into a tidy 400 response in one place. Handlers on a blueprint only cover that blueprint's routes; handlers on the app cover everything. For an API return JSON and for a website return a friendly template, and in both cases be careful not to leak stack traces or internal messages to visitors.

A 500 error means your code has a bug. In production Flask logs the traceback and shows the generic 500 page or your handler, while in debug mode it shows the interactive debugger instead, so never expose that. The runnable block builds the lookup rule Flask uses: walk up the exception's class hierarchy until a registered handler is found, with a fallback of 500. This is why a handler for a parent class also catches its subclasses.

Registering handlers (run on your computer)run on your computer
from flask import Flask, jsonify, render_template

app = Flask(__name__)


class ValidationError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.message = message


@app.errorhandler(404)
def not_found(error):
    return render_template("404.html"), 404


@app.errorhandler(ValidationError)
def invalid(error):
    return jsonify(error=error.message), 400


@app.errorhandler(500)
def server_error(error):
    app.logger.exception("Unhandled error")
    return jsonify(error="Something went wrong on our side."), 500


@app.post("/age")
def set_age():
    raise ValidationError("age must be a number")

Line by line

  1. 6-9A custom exception that carries a message for the client.
  2. 12-14A handler for the standard 404 status. It renders a template so a missing page still looks like your site.
  3. 17-19A handler for our own exception class turns it into a JSON 400 response.
  4. 22-25The 500 handler logs the full traceback for you, but returns only a generic message to the visitor.
  5. 28-30Any view can raise ValidationError; the handler decides how the user sees it.
How handler lookup works (runs in your browser)
class HTTPError(Exception):
    code = 500


class NotFound(HTTPError):
    code = 404


class BadRequest(HTTPError):
    code = 400


class MissingField(BadRequest):
    pass


handlers = {}


def errorhandler(exc_class):
    def decorator(func):
        handlers[exc_class] = func
        return func
    return decorator


@errorhandler(NotFound)
def handle_404(exc):
    return 404, "Page not found"


@errorhandler(BadRequest)
def handle_400(exc):
    return 400, f"Bad request: {exc}"


def run(view):
    try:
        return 200, view()
    except Exception as exc:
        for cls in type(exc).__mro__:
            if cls in handlers:
                return handlers[cls](exc)
        return 500, "Internal Server Error"


def ok():
    return "fine"


def missing_page():
    raise NotFound()


def missing_field():
    raise MissingField("email")


def bug():
    return 1 / 0


for view in (ok, missing_page, missing_field, bug):
    print(view.__name__, "->", run(view))
Expected output
ok -> (200, 'fine')
missing_page -> (404, 'Page not found')
missing_field -> (400, 'Bad request: email')
bug -> (500, 'Internal Server Error')

Line by line

  1. 1-12A small hierarchy of errors. MissingField is a kind of BadRequest, which is a kind of HTTPError.
  2. 15-21errorhandler registers a function for an exception class, the same shape as Flask's decorator.
  3. 24-31One handler for not-found and one for bad requests.
  4. 34-41run calls a view and, on an exception, walks the class's method resolution order (__mro__) from most specific to most general to find a handler. No handler means 500.
  5. 44-58Four views: one fine, one raising NotFound, one raising a subclass of BadRequest, and one with a genuine bug.
  6. 61-62MissingField has no handler of its own but is still handled, because its parent class has one. The division by zero ends up as 500.

Configuration and deployment basics

The built-in flask run server is for development only. A production setup puts your app behind a WSGI server such as Gunicorn (on Linux and macOS) or Waitress (which also works on Windows). WSGI is the standard interface between Python web servers and applications: the server calls your app as a function with the request details and a callback, and the app returns the response body. A Flask object is exactly such a callable, which is why any WSGI server can run it. Usually a reverse proxy like Nginx or the hosting platform's router sits in front to handle HTTPS and static files.

Configuration should come from the environment, not from your source code. Keep the secret key, database URL and debug flag in environment variables, and read them in the factory. Use a requirements.txt (or a pyproject.toml) with pinned versions so your server installs the same packages you tested with. Set DEBUG off, serve over HTTPS, set cookie flags such as SESSION_COOKIE_SECURE, and keep dependencies updated. Hosting products and their prices change often, so check the current documentation of the platform you choose.

The two runnable blocks show both ideas without a server. The first calls a plain WSGI application directly with a hand-made environ dictionary, which is what Gunicorn does for every request. The second loads typed configuration from an environment-like dictionary and fails early when a required value is missing. Failing at start-up with a clear message beats discovering a missing secret at the first login attempt.

wsgi.py and server commands (run on your computer)run on your computer
# wsgi.py contains:
#   from notes_app import create_app
#   app = create_app()

pip install gunicorn
export SECRET_KEY="a-long-random-value"
gunicorn --workers 3 --bind 127.0.0.1:8000 wsgi:app

# or, with the factory called directly:
gunicorn "notes_app:create_app()"

# on Windows
pip install waitress
waitress-serve --listen=127.0.0.1:8000 wsgi:app

Line by line

  1. 1-3A tiny wsgi.py exposes the application object that servers import.
  2. 5Install a production WSGI server.
  3. 6Provide secrets through the environment, not through code. Generate the value with a password manager or python -c "import secrets; print(secrets.token_hex(32))".
  4. 7Start three worker processes listening locally; a reverse proxy forwards public traffic to this address.
  5. 9-10Gunicorn can also call a factory expression directly.
  6. 12-14Waitress is a pure-Python alternative that works on Windows.
A WSGI application called by hand (runs in your browser)
from wsgiref.util import setup_testing_defaults


def application(environ, start_response):
    path = environ["PATH_INFO"]
    method = environ["REQUEST_METHOD"]
    body = f"{method} {path}".encode()
    start_response("200 OK", [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(body))),
    ])
    return [body]


def call(app, method, path):
    environ = {"REQUEST_METHOD": method, "PATH_INFO": path}
    setup_testing_defaults(environ)
    captured = {}

    def start_response(status, headers):
        captured["status"] = status
        captured["headers"] = dict(headers)

    chunks = app(environ, start_response)
    return captured["status"], captured["headers"]["Content-Type"], b"".join(chunks)


print(call(application, "GET", "/hello"))
print(call(application, "POST", "/orders"))
Expected output
('200 OK', 'text/plain', b'GET /hello')
('200 OK', 'text/plain', b'POST /orders')

Line by line

  1. 1setup_testing_defaults fills an environ dictionary with the standard WSGI keys.
  2. 4-11The WSGI contract: a callable taking environ and start_response, calling start_response with a status line and headers, and returning an iterable of bytes. A Flask app object does exactly this.
  3. 14-26call plays the server: it builds the environment, supplies a start_response that records what the app says, and collects the body chunks.
  4. 29-30Two simulated requests. No sockets are needed because the interface is only function calls.
Typed configuration from the environment (runs in your browser)
def load_config(env):
    missing = [key for key in ("SECRET_KEY", "DATABASE_URL") if not env.get(key)]
    if missing:
        raise RuntimeError("Missing settings: " + ", ".join(missing))
    return {
        "SECRET_KEY": env["SECRET_KEY"],
        "DATABASE_URL": env["DATABASE_URL"],
        "DEBUG": env.get("DEBUG", "0") in ("1", "true", "True"),
        "WORKERS": int(env.get("WORKERS", "3")),
    }


good = {"SECRET_KEY": "x" * 32, "DATABASE_URL": "sqlite:///app.db", "DEBUG": "true"}
config = load_config(good)
print({k: v for k, v in config.items() if k != "SECRET_KEY"})

try:
    load_config({"DATABASE_URL": "sqlite:///app.db"})
except RuntimeError as err:
    print("startup failed:", err)
Expected output
{'DATABASE_URL': 'sqlite:///app.db', 'DEBUG': True, 'WORKERS': 3}
startup failed: Missing settings: SECRET_KEY

Line by line

  1. 1-4Collect every missing required key and fail immediately with one clear message.
  2. 5-10Convert strings to the right types. Environment variables are always text, so "0" must not be treated as true.
  3. 13-15Load a valid configuration and print it without the secret.
  4. 17-20A missing secret stops the app at start-up instead of failing later.
⚠️

Deployment details such as platforms, commands and pricing change over time. Treat my commands as the general shape and check the current documentation of your server and host before going live.

Common mistakes

❌ Leaving debug mode on in production

The Werkzeug debugger can run arbitrary Python from the browser, so a public debug server is a remote-code-execution hole. Turn --debug off, run behind Gunicorn or Waitress, and keep the setting in an environment variable.

❌ Committing the secret key

If SECRET_KEY is in your repository anyone can forge session cookies. Read it from the environment, rotate it if it ever leaks, and keep a .env file out of version control.

❌ Putting user text into HTML with an f-string

Returning f"<p>{name}</p>" lets a visitor inject a script. Use templates, which autoescape, or markupsafe.escape, and never mark untrusted input as safe.

❌ Doing work on GET that should be a POST

Links can be prefetched, crawled and cached, so deleting or changing data on GET is risky. Use POST (with CSRF protection) for anything that changes state, and redirect afterwards.

❌ Creating one global app and importing it everywhere

A module-level app causes circular imports and makes tests share state. Use an application factory, blueprints and current_app, so each test can build a clean app.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What does @app.route("/about") do?

Q2. Which route only matches URLs such as /post/42 and passes an integer to the view?

Q3. Why should a successful form POST usually end with redirect(...)?

Q4. What is true about Flask's default session?

Q5. What is the main benefit of an application factory such as create_app()?

Q6. Which tool sends fake requests to a Flask app without starting a server?

Frequently asked questions

Neither is better in general. Flask is small and flexible, so you pick the database layer, forms and auth yourself, which suits small apps, APIs and learning. Django includes an ORM, admin, auth and forms out of the box, which saves time on large database-driven sites. See Django Web Framework to compare.

Yes. Return a dictionary or jsonify(...) from a view and Flask sends JSON. For APIs with automatic validation and generated documentation, many people also look at FastAPI, but Flask is perfectly capable.

Flask has no database layer of its own. You can use Python's built-in sqlite3 (see SQLite Databases) or an extension such as Flask-SQLAlchemy. Create the connection per request or per app context and close it afterwards.

Common causes are a missing or extra trailing slash, a converter that does not match (<int:id> with letters), the blueprint's url_prefix, or a view in a module that was never imported. Run flask --app yourapp routes to list the registered rules.

No. A web server needs sockets and processes that a browser tab cannot provide, so the Flask examples are copy-and-run code for your computer. The from-scratch examples on this page do run in the browser and teach the same ideas.

Key takeaways

  • βœ“A Flask app maps URLs to ordinary Python functions with @app.route, and what the function returns becomes the HTTP response.
  • βœ“Use converters like <int:id> for variables, request.args, request.form and request.get_json() for input, and jsonify or tuples for output.
  • βœ“Render HTML with Jinja2 templates and inheritance; autoescaping protects you, so do not mark user input as safe.
  • βœ“Validate forms on the server, redirect after a successful POST, hash passwords, and remember that the session cookie is signed but readable.
  • βœ“Structure growing apps with blueprints and an application factory, then test them quickly with app.test_client() and pytest.
  • βœ“Register error handlers, read configuration from the environment, turn debug off and serve through a WSGI server in production.