πΆοΈ 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.
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.
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
- 1Import the
Flaskclass, the heart of every application. - 3Create the application object.
__name__helps Flask locate resources relative to this file. - 5-7Register
homefor the URL/. Whatever string it returns becomes the body of the response. - 9-11A second route. Returning a string containing HTML is fine; Flask sends it with the
text/htmlcontent type.
python -m venv .venv source .venv/bin/activate pip install flask flask --app hello run --debug
Line by line
- 1-2Create and activate a virtual environment so Flask is installed for this project only (on Windows use
.venv\Scripts\activate). - 3Install Flask and its dependencies.
- 4Run the app from
hello.py. The server listens on port 5000 by default and reloads when you save a file.
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))(200, 'Hello from MiniApp')
(405, 'Method Not Allowed')
(200, 'Saved!')
(404, 'Not Found')
[('GET', '/'), ('POST', '/save')]Line by line
- 1-3The app keeps one dictionary that maps
(method, path)pairs to view functions. - 5-10
routeis a decorator factory: callingapp.route(path)returnsdecorator, which records the function and hands it back unchanged. - 12-18
handleplays the role of the web server. A match runs the view; a known path with the wrong method gives 405; anything else gives 404. - 21Create one app instance, just like
Flask(__name__). - 24-31Register two views. The second only accepts
POST, mirroringmethods=["POST"]in Flask. - 34-38Try four requests, then list the registered keys. Notice that a GET to
/saveis 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.
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-2
url_forbuilds URLs from view names;escapemakes text safe to place in HTML. - 6-8The
<username>part is captured and passed in as theusernameargument. It is escaped before going into the HTML. - 10-12With the
intconverter,/post/42givespost_id == 42as an integer and/post/abcis a 404. - 14-16The
pathconverter accepts slashes, so/files/img/2024/a.pngmatches withsubpath == "img/2024/a.png". - 18-20
url_for("show_post", post_id=7)returns/post/7. Building links withurl_formeans a changed rule never leaves broken links behind.
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")){'username': 'ana'}
{'post_id': 42}
None
{'subpath': 'img/2024/a.png'}
{'year': 2025, 'month': 11}Line by line
- 3-7Each converter pairs a regular-expression fragment with a function that converts the matched text.
- 10-22
compile_rulerewrites every<converter:name>in the rule into a named regex group and remembers which cast belongs to which name. - 17The substitution regex reads an optional
converter:prefix followed by the variable name. - 25-30
matchapplies the compiled pattern to a URL. A failed match returnsNone; a successful one returns a dictionary of converted values. - 33-37Five trial matches. The
intconverter rejectsfortybecause\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.
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 respLine by line
- 1Import the request proxy and the common response helpers.
- 5-9Read optional query parameters.
type=intconvertspageand falls back to the default if the value is not a number. - 11-16Parse a JSON body.
silent=TruereturnsNoneinstead of raising when the body is missing or invalid, so we can answer with our own 400 message. The tuple adds a status code. - 18-20Redirect to another view by name. The browser then makes a new GET request to
/search. - 22-26Build a response object by hand so a cookie can be attached.
httponlyhides it from JavaScript andsamesitelimits cross-site sending.
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="{}"))--> 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
- 6-20
Requestbundles what arrived: method, URL and body.pathandargsare computed from the URL, likerequest.pathandrequest.argsin Flask. - 23-26
Responseholds a body, a status code and headers, with HTML as the default content type. - 29-41
make_responseis the normaliser: a readyResponsepasses through, a tuple sets the status, a dict becomes JSON, and anything else becomes text. - 44-52Three views written exactly as you would write Flask views: they return a dict, a tuple, or a string.
- 55-61The dispatcher looks up the view, normalises the result and prints both sides of the exchange.
- 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.
<!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-3A normal HTML skeleton. Nothing special yet.
- 5
{% block title %}defines a hole that child templates may override; the text inside is the default. - 6
url_for('static', ...)generates the URL of a file inside yourstatic/folder. - 9Links are built from view names, so they survive route changes.
- 11The main hole that every page fills with its own content.
{% 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
- 1Inherit the skeleton from
base.html. - 2Override the title block, using a variable from the view.
- 4Print a variable and pass it through the
titlefilter. - 5-13Branch with
if, loop withfor.loop.indexcounts from 1. Output is escaped automatically, so<b>in a title shows as text.
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-3Import
render_templateand create the app. - 6-9Build plain Python data. Templates can read dictionary keys with dot syntax, so
item.titleworks. - 10Render the template, passing keyword arguments that become template variables.
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)<h1>My notes</h1> <ul> <li class="open">Buy rice</li> <li class="done">Write lesson <3</li> <li class="open">Say "hi" & wave</li> </ul> Hello Ana, you have $count notes missing placeholder: 'name'
Line by line
- 1-2
string.Templateuses$nameplaceholders;htmlprovidesescape. - 4-5One template for the whole page and one for each list row.
- 7Sample data, including characters that are special in HTML.
- 8-11Build the rows in Python.
html.escapeconverts<,>,&and quotes into safe entities, which is what Jinja2 autoescaping does for you. - 12Substitute the finished rows into the page and print the HTML.
- 14
safe_substituteleaves unknown placeholders alone instead of failing. - 15-18
substituteis strict: a missing value raisesKeyError. 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.
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-4Imports, including Werkzeug's password helpers.
- 6-7The secret key signs the session cookie. Read it from the environment so it never lives in your repository.
- 9A stand-in user table that holds a hash of the password, never the password itself. Use a real database in a real app.
- 11-14One view handles both methods.
errorstarts empty for a fresh GET. - 15-17Read submitted fields with
.get()and sensible defaults. - 18-22If the user exists and the hash matches, store the username in the session, queue a flash message and redirect (post/redirect/get).
- 23-24Otherwise show the form again with one generic message. Saying only "invalid username or password" avoids revealing which one was wrong.
- 26-31A protected page: no
userin the session means a redirect to the login form. - 33-36Logging out clears the session. It is a POST because it changes state.
{% 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
- 4-6Show any queued flash messages once; they are removed after being read.
- 7Show the error, if the view passed one.
- 8-12A plain POST form. With no
actionattribute it submits to the same URL. Real apps should add a CSRF token, for example with the Flask-WTF extension.
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))loads fine: {'admin': False, 'user': 'ana'}
anyone can read it: {"admin": false, "user": "ana"}
forged payload, old signature: None
same payload, wrong key: NoneLine by line
- 1-6Only the standard library is needed. The secret is a fixed example here; a real key is long, random and private.
- 9-10The signature is an HMAC-SHA256 of the payload, which only someone with the secret can compute.
- 13-16
signserialises the data, encodes it so it is safe in a cookie, and appends the signature after a dot. - 19-23
loadrecomputes the signature and compares in constant time. A mismatch means the cookie was changed, so we returnNone. - 26-27A valid cookie round-trips.
- 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.
- 32-34An attacker flips
adminto true but cannot produce a matching signature, so both forgery attempts are rejected.
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)){'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-5A form post body looks like a query string,
name=Ana&age=29.parse_qssplits it, and we keep the first value of each field, likerequest.form. - 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. - 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.
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.pyLine by line
- 1-3The package folder;
__init__.pyholds the factory. - 4-5One module per blueprint keeps related routes together.
- 6-9Templates live in a folder named after the blueprint to avoid clashing names.
- 10-11Tests and a small
wsgi.pyentry point for production servers sit outside the package.
# 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-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.
- 16-20A blueprint with a URL prefix. Its routes become
/blog/and/blog/<id>. - 23-25
indexreturns the sorted post ids as JSON. - 28-33
abort(404)stops the view and triggers Flask's not-found handling. - 37-44Inside a view,
current_apppoints to the app handling this request, which is how blueprints read configuration without importing the app.
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"))['/api/status', '/blog/']
Hello from the blog
Test from the blog
{'debug': False} {'debug': True}
404 Not FoundLine by line
- 1-12A blueprint just collects
(path, view)pairs and remembers a URL prefix. Nothing runs until an app registers it. - 15-28The app has its own config dictionary and route table. Registering a blueprint copies each rule in with the prefix added.
- 31-32Two blueprints are created once, at import time.
- 35-42Views receive the app so they can read configuration, standing in for
current_appin Flask. - 45-49The factory builds a new app each time it is called.
- 52-53Two separate apps from the same blueprints: one with defaults, one for testing.
- 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.
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-2Import pytest and the factory, not a global
app. - 5-7The
appfixture builds a new application with test settings for every test. - 10-12The
clientfixture wraps it in the test client. - 15-18Request a URL and check the status code and the parsed JSON body.
- 21-23Check the value for a specific post.
- 26-27A missing post should give 404, which
abort(404)produces. - 30-31Proof that the config override reached the blueprint through
current_app.
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))tests run: 3 all passed: True failures: 0 errors: 0
Line by line
- 1-2
unittestships with Python, andiolets us capture the runner's chatter. - 5-9A deliberately tiny app with a
test_client()method, mimicking Flask. - 12-18The client answers a GET without any network and returns a status code and data.
- 21-23
setUpruns before every test, so each test starts with a fresh app and client. - 25-33Three tests using
assertEqual, the same style as asserting on a Flask response. - 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.
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
- 6-9A custom exception that carries a message for the client.
- 12-14A handler for the standard 404 status. It renders a template so a missing page still looks like your site.
- 17-19A handler for our own exception class turns it into a JSON 400 response.
- 22-25The 500 handler logs the full traceback for you, but returns only a generic message to the visitor.
- 28-30Any view can raise
ValidationError; the handler decides how the user sees it.
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))ok -> (200, 'fine') missing_page -> (404, 'Page not found') missing_field -> (400, 'Bad request: email') bug -> (500, 'Internal Server Error')
Line by line
- 1-12A small hierarchy of errors.
MissingFieldis a kind ofBadRequest, which is a kind ofHTTPError. - 15-21
errorhandlerregisters a function for an exception class, the same shape as Flask's decorator. - 24-31One handler for not-found and one for bad requests.
- 34-41
runcalls 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. - 44-58Four views: one fine, one raising
NotFound, one raising a subclass ofBadRequest, and one with a genuine bug. - 61-62
MissingFieldhas 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 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-3A tiny
wsgi.pyexposes the application object that servers import. - 5Install a production WSGI server.
- 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))". - 7Start three worker processes listening locally; a reverse proxy forwards public traffic to this address.
- 9-10Gunicorn can also call a factory expression directly.
- 12-14Waitress is a pure-Python alternative that works on Windows.
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"))('200 OK', 'text/plain', b'GET /hello')
('200 OK', 'text/plain', b'POST /orders')Line by line
- 1
setup_testing_defaultsfills anenvirondictionary with the standard WSGI keys. - 4-11The WSGI contract: a callable taking
environandstart_response, callingstart_responsewith a status line and headers, and returning an iterable of bytes. A Flask app object does exactly this. - 14-26
callplays the server: it builds the environment, supplies astart_responsethat records what the app says, and collects the body chunks. - 29-30Two simulated requests. No sockets are needed because the interface is only function calls.
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){'DATABASE_URL': 'sqlite:///app.db', 'DEBUG': True, 'WORKERS': 3}
startup failed: Missing settings: SECRET_KEYLine by line
- 1-4Collect every missing required key and fail immediately with one clear message.
- 5-10Convert strings to the right types. Environment variables are always text, so
"0"must not be treated as true. - 13-15Load a valid configuration and print it without the secret.
- 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?
<int:post_id> uses the int converter. A request like /post/abc does not match, so Flask returns 404.Q3. Why should a successful form POST usually end with redirect(...)?
Q4. What is true about Flask's default session?
SECRET_KEY, not encrypted. That is why you store a user id and never a secret.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
Is Flask better than Django?
+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.
Can I use Flask for a JSON API?
+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.
How do I connect a database?
+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.
Why do I get a 404 for a route I defined?
+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.
Can I run Flask in the browser on this site?
+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.formandrequest.get_json()for input, andjsonifyor 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.