Contents

Flask Cheat Sheet

Flask from the first route to a deployable app: routing, requests and responses, Jinja templates, blueprints and the application factory, sessions, databases, logins, JSON APIs and tests. Every example with output ran on Flask 3.1.3, Werkzeug 3.1.9 and Python 3.14 through Flask's test client.

By Bogdan SanduUpdated December 2, 2026Tested on Flask 3.1.3

Flask route tester

Type a route rule and some URLs, one per line, and see which ones match and what each converter returns. The matching follows Werkzeug's converters and trailing slash rules.

Result

Flask app starter

Choose what your app needs and copy an application factory that wires it together.

shop/__init__.py

    

Install & First App

Install

Create a virtual environment and install Flask

Flask 3.1 needs Python 3.9 or newer. flask --version prints the Python, Flask and Werkzeug versions, which is the first thing to check when an example does not work.

$ python3 -m venv .venv
$ source .venv/bin/activate        # Windows: .venv\Scripts\activate
$ pip install flask
$ flask --version

Hello, Flask

The smallest app

The output under the examples on this page comes from Flask's test client, which sends a real request through the app without starting a server.

app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello, Flask"GET / -> 200 OK
  Content-Type: text/html; charset=utf-8
  Hello, Flask

Run the development server

--debug turns on the reloader and the interactive debugger. Never expose the development server or debug mode to the internet; use a production server such as Gunicorn.

$ flask --app app run --debug
$ flask --app app run --host 0.0.0.0 --port 8000
$ python -m flask --app app run

What flask run looks for

You runFlask loads
flask run in a folder with app.py or wsgi.pyThat file
flask --app hello runhello.py, or the hello package
flask --app hello:app runThe app object in hello
flask --app "hello:create_app()" runThe app returned by a factory

Routing

Routes and methods

Variables and converters

A converter both checks and converts the value: /users/ann does not match int, so Flask returns 404 instead of calling the view.

from flask import Flask

app = Flask(__name__)

@app.route("/users/<int:user_id>")
def user(user_id):
    return f"user {user_id} is {type(user_id).__name__}"

@app.route("/files/<path:name>")
def file(name):
    return f"file {name}"GET /users/42 -> 200 OK
  user 42 is int
GET /users/ann -> 404 NOT FOUND
  (HTML page: 404 Not Found)
GET /files/docs/a/b.txt -> 200 OK
  file docs/a/b.txt

Converters

ConverterMatches
stringAny text without a slash, the default
intPositive integers
floatPositive floating point numbers
pathText including slashes
uuidUUID strings, converted to uuid.UUID
any(a, b)One of the listed values

Methods, and the shortcut decorators

A method a route does not list returns 405 Method Not Allowed. @app.get and @app.post are shortcuts for route with one method.

from flask import Flask, request

app = Flask(__name__)

@app.route("/login", methods=["GET", "POST"])
def login():
    return "form" if request.method == "GET" else "logged in"

@app.get("/items")
def list_items():
    return ["a", "b"]

@app.post("/items")
def add_item():
    return {"created": True}, 201GET /login -> 200 OK
  form
POST /login -> 200 OK
  logged in
POST /items -> 201 CREATED
  {"created": true}
DELETE /items -> 405 METHOD NOT ALLOWED
  (HTML page: 405 Method Not Allowed)

Trailing slashes

A rule that ends in a slash works like a folder: the URL without the slash redirects to it. A rule without the slash returns 404 when the slash is added.

from flask import Flask

app = Flask(__name__)

@app.route("/projects/")
def projects():
    return "with slash"

@app.route("/about")
def about():
    return "without slash"GET /projects -> 308 PERMANENT REDIRECT
  Location: http://localhost/projects/
  (HTML page: Redirecting...)
GET /about/ -> 404 NOT FOUND
  (HTML page: 404 Not Found)

Custom converters

Register the converter before the routes that use it. to_url makes url_for build the URL from a list.

from flask import Flask
from werkzeug.routing import BaseConverter

class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split("+")
    def to_url(self, values):
        return "+".join(values)

app = Flask(__name__)
app.url_map.converters["list"] = ListConverter

@app.get("/tags/<list:tags>")
def tags(tags):
    return {"tags": tags}GET /tags/python+flask+web -> 200 OK
  {"tags": ["python", "flask", "web"]}

One view, several URLs

add_url_rule is what the decorator calls under the hood; it is handy for registering views built in a loop or imported from elsewhere.

from flask import Flask

app = Flask(__name__)

@app.route("/blog/", defaults={"page": 1})
@app.route("/blog/page/<int:page>")
def blog(page):
    return f"page {page}"

def health():
    return "ok"

app.add_url_rule("/healthz", "health", health)GET /blog/ -> 200 OK
  page 1
GET /blog/page/3 -> 200 OK
  page 3
GET /healthz -> 200 OK
  ok

Build URLs

url_for and redirect

url_for takes the view function's name, not the URL, so URLs keep working when you change a route. Extra arguments become the query string.

from flask import Flask, url_for, redirect

app = Flask(__name__)

@app.route("/users/<int:user_id>")
def profile(user_id):
    return f"profile {user_id}"

@app.route("/me")
def me():
    return redirect(url_for("profile", user_id=7, tab="posts"))

with app.test_request_context():
    print(url_for("profile", user_id=7))
    print(url_for("profile", user_id=7, _external=True))
    print(url_for("static", filename="app.css"))/users/7
http://localhost/users/7
/static/app.css
GET /me -> 302 FOUND
  Location: /users/7?tab=posts
  (HTML page: Redirecting...)

Request Data

Read what the client sent

Query string, form and JSON

get(..., type=int) falls back to the default when the value does not convert. Indexing a missing form key raises a KeyError that Flask turns into 400 Bad Request.

from flask import Flask, request

app = Flask(__name__)

@app.get("/search")
def search():
    q = request.args.get("q", "")
    page = request.args.get("page", 1, type=int)
    tags = request.args.getlist("tag")
    return {"q": q, "page": page, "tags": tags}

@app.post("/signup")
def signup():
    return {"email": request.form["email"], "plan": request.form.get("plan", "free")}

@app.post("/api/orders")
def order():
    data = request.get_json()
    return {"items": len(data["items"])}, 201GET /search?q=flask&page=2&tag=web&tag=api -> 200 OK
  {"page": 2, "q": "flask", "tags": ["web", "api"]}
GET /search?page=abc -> 200 OK
  {"page": 1, "q": "", "tags": []}
POST /signup -> 200 OK
  {"email": "ann@example.com", "plan": "free"}
POST /signup -> 400 BAD REQUEST
  (HTML page: 400 Bad Request)
POST /api/orders -> 201 CREATED
  {"items": 3}

Headers, cookies and the client

Header names are case-insensitive. request.is_json is True only when the Content-Type is JSON.

from flask import Flask, request

app = Flask(__name__)

@app.get("/whoami")
def whoami():
    return {
        "agent": request.headers.get("User-Agent"),
        "token": request.headers.get("Authorization", "").removeprefix("Bearer "),
        "theme": request.cookies.get("theme", "light"),
        "is_json": request.is_json,
        "path": request.path,
        "full": request.full_path,
    }GET /whoami?x=1 -> 200 OK
  {"agent": "curl/8.12", "full": "/whoami?x=1", "is_json": false, "path": "/whoami", "theme": "dark", "token": "abc123"}

Everything on the request object

AttributeHolds
request.methodGET, POST and so on
request.argsQuery string parameters
request.formForm fields from a POST
request.filesUploaded files
request.get_json()Parsed JSON body; 415 if the content type is not JSON
request.get_json(silent=True)None instead of an error for a bad body
request.headersRequest headers
request.cookiesCookies
request.path, request.urlPath and full URL
request.remote_addrClient IP, or the proxy's without ProxyFix

Responses

Return values

Strings, dicts, lists and tuples

A dict or list is turned into JSON automatically. A tuple can add a status code, headers, or both.

from flask import Flask

app = Flask(__name__)

@app.get("/text")
def text():
    return "plain text"

@app.get("/json")
def data():
    return {"ok": True, "n": 3}

@app.get("/created")
def created():
    return {"id": 9}, 201, {"Location": "/items/9"}GET /text -> 200 OK
  Content-Type: text/html; charset=utf-8
  plain text
GET /json -> 200 OK
  Content-Type: application/json
  {"n": 3, "ok": true}
GET /created -> 201 CREATED
  Location: /items/9
  {"id": 9}

Build a response object

abort raises an HTTP error immediately, so code after it never runs.

from flask import Flask, make_response, abort

app = Flask(__name__)

@app.get("/report")
def report():
    resp = make_response("a,b\n1,2\n")
    resp.headers["Content-Type"] = "text/csv"
    resp.set_cookie("seen", "1", max_age=3600, httponly=True, samesite="Lax")
    return resp

@app.get("/secret")
def secret():
    abort(403)GET /report -> 200 OK
  Content-Type: text/csv
  Set-Cookie: seen=1; Expires=Wed, 02 Dec 2026 17:09:29 GMT; Max-Age=3600; HttpOnly; Path=/; SameSite=Lax
  a,b
  1,2
GET /secret -> 403 FORBIDDEN

jsonify and response headers

Flask sorts JSON keys by default; app.json.sort_keys = False keeps them in the order you wrote them. jsonify returns a Response object you can add headers to.

from flask import Flask, jsonify

app = Flask(__name__)
app.json.sort_keys = False

@app.get("/list")
def as_list():
    resp = jsonify(total=2, items=["b", "a"])
    resp.headers["Cache-Control"] = "public, max-age=60"
    return respGET /list -> 200 OK
  Content-Type: application/json
  Cache-Control: public, max-age=60
  {"total": 2, "items": ["b", "a"]}

Send files and stream

send_from_directory refuses paths that escape the folder, which makes it the safe choice for names that come from the URL. A generator streams the response without building it in memory.

from flask import Flask, send_file, send_from_directory, Response

app = Flask(__name__)

@app.get("/download/<path:name>")
def download(name):
    return send_from_directory("exports", name, as_attachment=True)

@app.get("/numbers")
def numbers():
    def gen():
        for i in range(3):
            yield f"{i}\n"
    return Response(gen(), mimetype="text/plain")

Templates (Jinja)

Render templates

render_template and the templates folder

Flask looks for templates in a folder called templates next to the app module. Every keyword argument becomes a variable in the template.

app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.get("/hello/<name>")
def hello(name):
    return render_template("hello.html", name=name, items=["a", "b"])

Variables, loops, conditions and filters

Jinja escapes HTML in variables, so the bio prints as text, not markup. The - inside {%- and -%} trims whitespace around the tag.

from flask import Flask, render_template_string

app = Flask(__name__)
TPL = """{% if user %}Hi {{ user.name|title }}!{% else %}Hi guest!{% endif %}
{% for item in items -%}
{{ loop.index }}. {{ item|upper }}{{ ", " if not loop.last }}
{%- endfor %}
{{ price|round(2) }} | {{ missing|default("n/a") }} | {{ tags|join(" / ") }} | {{ bio }}"""

with app.app_context():
    print(render_template_string(TPL, user={"name": "ann lee"}, items=["tea", "cake"],
                                 price=3.14159, tags=["x", "y"], bio="<b>hi</b>"))Hi Ann Lee!
1. TEA, 2. CAKE
3.14 | n/a | x / y | &lt;b&gt;hi&lt;/b&gt;

Template inheritance

templates/base.html
<!doctype html>
<title>{% block title %}My app{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}">
<main>{% block content %}{% endblock %}</main>

A page that extends the base

templates/hello.html
{% extends "base.html" %}
{% block title %}Hello {{ name }}{% endblock %}
{% block content %}
  <h1>Hello, {{ name }}</h1>
  {% include "_items.html" %}
{% endblock %}

Custom filters and values in every template

A context processor returns a dict that is merged into every template, which suits the site name, the current user or feature flags.

from flask import Flask, render_template_string

app = Flask(__name__)

@app.template_filter("money")
def money(value, currency="$"):
    return f"{currency}{value:,.2f}"

@app.context_processor
def inject_globals():
    return {"site_name": "Shop", "year": 2026}

with app.app_context():
    print(render_template_string("{{ site_name }} {{ year }}: {{ 1234.5|money }} {{ 99|money('EUR ') }}"))Shop 2026: $1,234.50 EUR 99.00

Macros and safe HTML

Only mark HTML as safe, with Markup or the |safe filter, when you produced it yourself. Doing it to user input opens the page to cross-site scripting.

from flask import Flask, render_template_string
from markupsafe import Markup

app = Flask(__name__)
TPL = """{% macro field(name, type="text") -%}
<input name="{{ name }}" type="{{ type }}">
{%- endmacro %}{{ field("email", "email") }}
{{ trusted }} {{ untrusted }}"""

with app.app_context():
    print(render_template_string(TPL, trusted=Markup("<em>ok</em>"), untrusted="<em>no</em>"))<input name="email" type="email">
<em>ok</em> &lt;em&gt;no&lt;/em&gt;

Error Handling

Handle errors

Custom error pages and JSON errors

A handler for a status code wins over one for a whole exception class. Registering one for HTTPException turns every HTTP error into JSON, which suits an API.

from flask import Flask, abort, request
from werkzeug.exceptions import HTTPException

app = Flask(__name__)

@app.errorhandler(404)
def not_found(e):
    return {"error": "not found", "path": request.path}, 404

@app.errorhandler(HTTPException)
def http_error(e):
    return {"error": e.name, "code": e.code, "message": e.description}, e.code

@app.get("/items/<int:item_id>")
def item(item_id):
    if item_id != 1:
        abort(404)
    return {"id": 1}

@app.delete("/items/<int:item_id>")
def delete(item_id):
    abort(409, description="item is locked")GET /items/1 -> 200 OK
  {"id": 1}
GET /items/2 -> 404 NOT FOUND
  {"error": "not found", "path": "/items/2"}
DELETE /items/1 -> 409 CONFLICT
  {"code": 409, "error": "Conflict", "message": "item is locked"}

Your own exception class

from flask import Flask

app = Flask(__name__)

class PaymentError(Exception):
    def __init__(self, message, status=402):
        super().__init__(message)
        self.status = status

@app.errorhandler(PaymentError)
def payment_error(e):
    return {"error": str(e)}, e.status

@app.post("/pay")
def pay():
    raise PaymentError("card declined")POST /pay -> 402 PAYMENT REQUIRED
  {"error": "card declined"}

Forms & CSRF (Flask-WTF)

Validated forms

A form class with validators

validate_on_submit is True only for a POST with valid data. CSRF is switched off here only so the example can post without a token; keep it on in your app. The Email validator needs the email-validator package.

from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, Email, NumberRange

app = Flask(__name__)
app.config.update(SECRET_KEY="dev-only", WTF_CSRF_ENABLED=False)

class SignupForm(FlaskForm):
    email = StringField("Email", validators=[DataRequired(), Email()])
    age = IntegerField("Age", validators=[NumberRange(min=16)])

@app.post("/signup")
def signup():
    form = SignupForm()
    if form.validate_on_submit():
        return {"ok": True, "email": form.email.data}
    return {"errors": form.errors}, 422POST /signup -> 422 UNPROCESSABLE ENTITY
  {"errors": {"age": ["Number must be at least 16."], "email": ["Invalid email address."]}}
POST /signup -> 200 OK
  {"email": "ann@example.com", "ok": true}

The CSRF token in the template

hidden_tag renders the hidden csrf_token field. For forms that are not FlaskForms, and for AJAX calls, enable CSRFProtect(app) and send the token from csrf_token() in a header.

<form method="post">
  {{ form.hidden_tag() }}
  {{ form.email.label }} {{ form.email(size=32) }}
  {% for error in form.email.errors %}<p class="error">{{ error }}</p>{% endfor %}
  <button>Sign up</button>
</form>

Configuration

Set configuration

Ways to fill app.config

from_prefixed_env reads every environment variable that starts with FLASK_, drops the prefix and parses values as JSON where it can, so 1048576 arrives as an int. Keep secrets in the environment, never in code.

import os
from flask import Flask

os.environ["FLASK_SECRET_KEY"] = "change-me"
os.environ["FLASK_MAX_CONTENT_LENGTH"] = "1048576"

app = Flask(__name__)
app.config.from_mapping(APP_NAME="shop", ITEMS_PER_PAGE=20)
app.config.from_prefixed_env()

print(app.config["APP_NAME"], app.config["ITEMS_PER_PAGE"])
print(app.config["SECRET_KEY"])
print(app.config["MAX_CONTENT_LENGTH"], type(app.config["MAX_CONTENT_LENGTH"]).__name__)
print(app.config["DEBUG"], app.config["TESTING"])shop 20
change-me
1048576 int
False False

Other loaders

from_pyfile and the instance folder are handy for settings that differ per machine and stay out of version control.

app.config.from_object("config.ProductionConfig")
app.config.from_pyfile("settings.cfg", silent=True)
app.config.from_file("config.json", load=json.load)
app.config.from_file("config.toml", load=tomllib.load, text=False)

Built-in settings worth knowing

KeyDefaultPurpose
SECRET_KEYNoneSigns the session cookie; required for sessions and flash
SECRET_KEY_FALLBACKSNoneOld keys still accepted while rotating (3.1)
DEBUGFalseSet by --debug; never on in production
TESTINGFalseLets exceptions reach the test client
MAX_CONTENT_LENGTHNoneLargest request body in bytes
MAX_FORM_MEMORY_SIZE500000Largest non-file form field in bytes (3.1)
SESSION_COOKIE_SECUREFalseSend the session cookie over HTTPS only
SESSION_COOKIE_SAMESITENoneLax or Strict for CSRF protection
PERMANENT_SESSION_LIFETIME31 daysLifetime of permanent sessions
TRUSTED_HOSTSNoneAllowed Host header values (3.1)

Load .env files

With python-dotenv installed, the flask command loads .flaskenv and .env automatically. Commit .flaskenv for public settings; keep .env out of git.

$ pip install python-dotenv
$ echo 'FLASK_APP=app' >> .flaskenv
$ echo 'FLASK_SECRET_KEY=dev-only' >> .env
$ flask run
$ flask -e staging.env run

Application Factory

Build the app in a function

create_app

A factory lets tests create a fresh app with their own config, and avoids circular imports because blueprints are imported inside the function. Run it with flask --app shop run, which finds create_app on its own.

shop/__init__.py
from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY="dev", DATABASE="shop.sqlite")
    if test_config is None:
        app.config.from_pyfile("config.py", silent=True)
    else:
        app.config.from_mapping(test_config)

    from . import auth, orders
    app.register_blueprint(auth.bp)
    app.register_blueprint(orders.bp)

    @app.get("/health")
    def health():
        return {"status": "ok"}

    return app

Project layout

shop/
  __init__.py        create_app
  auth.py            blueprint
  orders.py          blueprint
  models.py
  templates/
  static/
instance/
  config.py          secrets, not in git
tests/
  conftest.py
pyproject.toml

Extensions that work with a factory

Create extensions at module level without an app, then bind them inside the factory with init_app.

from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()
login_manager = LoginManager()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    login_manager.init_app(app)
    return app

Blueprints

Split the app into blueprints

Define and register a blueprint

Endpoints inside a blueprint get the blueprint name as a prefix, so url_for("orders.index"). Inside the blueprint, .detail is a shortcut for the current blueprint. Registering the same blueprint twice needs a different name.

from flask import Flask, Blueprint, url_for

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

@bp.get("/")
def index():
    return ["o1", "o2"]

@bp.get("/<order_id>")
def detail(order_id):
    return {"id": order_id, "self": url_for(".detail", order_id=order_id)}

app = Flask(__name__)
app.register_blueprint(bp)
app.register_blueprint(bp, url_prefix="/v2/orders", name="orders_v2")

with app.test_request_context():
    print(url_for("orders.index"), url_for("orders_v2.detail", order_id="o1"))/orders/ /v2/orders/o1
GET /orders/o9 -> 200 OK
  {"id": "o9", "self": "/orders/o9"}

Contexts, g & Request Hooks

Contexts and g

Request hooks and g

g lives for one request and is the place for things like the current user or a database connection. after_request must return the response.

import time
from flask import Flask, g

app = Flask(__name__)

@app.before_request
def start_timer():
    g.start = time.perf_counter()
    g.user = "ann"

@app.after_request
def add_header(resp):
    resp.headers["X-Elapsed-Ms"] = "0" if time.perf_counter() - g.start < 1 else "slow"
    return resp

@app.get("/")
def index():
    return f"hello {g.user}"GET / -> 200 OK
  X-Elapsed-Ms: 0
  hello ann

Async views

Async views need pip install "flask[async]". Each request still runs in a worker thread, so async helps when one request waits on several things at once, not for raw throughput; for a fully async app consider Quart.

import asyncio
from flask import Flask

app = Flask(__name__)

@app.get("/both")
async def both():
    async def fetch(name, delay):
        await asyncio.sleep(delay)
        return name
    results = await asyncio.gather(fetch("users", 0.05), fetch("orders", 0.05))
    return {"results": results}GET /both -> 200 OK
  {"results": ["users", "orders"]}

Logging

app.logger writes to stderr by default. Use %s placeholders instead of f-strings so the message is only built when the level is enabled.

import logging
from flask import Flask

app = Flask(__name__)
app.logger.setLevel(logging.INFO)

@app.get("/charge")
def charge():
    app.logger.info("charging order %s", 42)
    app.logger.warning("card expires soon")
    return "ok"

app.test_client().get("/charge")[2026-12-02 18:09:36,334] INFO in app: charging order 42
[2026-12-02 18:09:36,334] WARNING in app: card expires soon

Use current_app outside a request

Scripts, background jobs and tests that touch current_app, g or the database need with app.app_context():. The flask command and the test client push it for you.

from flask import Flask, current_app

app = Flask(__name__)
app.config["APP_NAME"] = "shop"

def app_name():
    return current_app.config["APP_NAME"]

try:
    app_name()
except RuntimeError as e:
    print(str(e).splitlines()[0])

with app.app_context():
    print(app_name())Working outside of application context.
shop

Sessions, Cookies & Flash

Sessions and flash messages

Store data in the session

The default session is a signed cookie: the user can read it but not change it. Assign the list back to session after changing it, because mutating it in place is not detected.

from flask import Flask, session

app = Flask(__name__)
app.secret_key = "dev-only-change-me"

@app.post("/cart/<item>")
def add(item):
    cart = session.get("cart", [])
    cart.append(item)
    session["cart"] = cart
    return {"cart": cart}

@app.get("/cart")
def cart():
    return {"cart": session.get("cart", [])}POST /cart/tea -> 200 OK
  {"cart": ["tea"]}
POST /cart/cake -> 200 OK
  {"cart": ["tea", "cake"]}
GET /cart -> 200 OK
  {"cart": ["tea", "cake"]}

Flash a message for the next page

A flashed message is shown once and then removed, so the second request gets an empty list.

from flask import Flask, flash, redirect, url_for, get_flashed_messages

app = Flask(__name__)
app.secret_key = "dev-only-change-me"

@app.post("/save")
def save():
    flash("Saved", "success")
    return redirect(url_for("done"))

@app.get("/done")
def done():
    return {"messages": get_flashed_messages(with_categories=True)}GET /done -> 200 OK
  {"messages": [["success", "Saved"]]}
GET /done -> 200 OK
  {"messages": []}

Database (Flask-SQLAlchemy)

Models and queries

Define a model and query it

This is the SQLAlchemy 2.x style that Flask-SQLAlchemy 3.1 uses: typed Mapped columns and db.select instead of the legacy User.query. Every database call needs an app context.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String

class Base(DeclarativeBase):
    pass

db = SQLAlchemy(model_class=Base)
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
db.init_app(app)

class User(db.Model):
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(String(120), unique=True)
    active: Mapped[bool] = mapped_column(default=True)

with app.app_context():
    db.create_all()
    db.session.add_all([User(email="ann@x.io"), User(email="bob@x.io", active=False)])
    db.session.commit()
    active = db.session.execute(db.select(User).filter_by(active=True)).scalars().all()
    print([u.email for u in active])
    user = db.session.get(User, 2)
    user.active = True
    db.session.commit()
    print(db.session.scalar(db.select(db.func.count()).select_from(User).where(User.active)))['ann@x.io']
2

In a view: 404s and pagination

db.paginate reads ?page= and ?per_page= from the request and returns 404 for a page past the end.

@app.get("/users/<int:user_id>")
def user(user_id):
    u = db.get_or_404(User, user_id)
    return {"email": u.email}

@app.get("/users")
def users():
    page = db.paginate(db.select(User).order_by(User.id), per_page=20)
    return {"items": [u.email for u in page.items], "pages": page.pages, "next": page.next_num}

Migrations with Flask-Migrate

Flask-Migrate wraps Alembic. Read every generated migration before you run upgrade: autogenerate misses some changes, such as renamed columns.

$ pip install flask-migrate
$ flask --app shop db init            # once, creates migrations/
$ flask --app shop db migrate -m "add users"
$ flask --app shop db upgrade
$ flask --app shop db downgrade

Authentication

Passwords and logins

Hash and check passwords

Werkzeug uses scrypt by default and stores the method and salt inside the hash string. Never store plain passwords or a fast hash like SHA-256.

from werkzeug.security import generate_password_hash, check_password_hash

h = generate_password_hash("correct horse battery staple")
print(h.split("$")[0])
print(check_password_hash(h, "correct horse battery staple"))
print(check_password_hash(h, "wrong"))scrypt:32768:8:1
True
False

Flask-Login

login_required returns 401 when nobody is logged in, or redirects to the page named in login_manager.login_view if you set one. user_loader rebuilds the user from the id stored in the session.

from flask import Flask
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user

app = Flask(__name__)
app.secret_key = "dev-only-change-me"
login_manager = LoginManager(app)

class User(UserMixin):
    def __init__(self, id):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User(user_id)

@app.post("/login")
def login():
    login_user(User("7"))
    return {"logged_in": True}

@app.get("/account")
@login_required
def account():
    return {"user": current_user.id}GET /account -> 401 UNAUTHORIZED
  (HTML page: 401 Unauthorized)
POST /login -> 200 OK
  {"logged_in": true}
GET /account -> 200 OK
  {"user": "7"}

JSON APIs

Build an API

A small CRUD resource

Only copy the fields you allow from the request body, as the PATCH does: here the client cannot change the id.

from flask import Flask, request, abort

app = Flask(__name__)
TODOS = {1: {"id": 1, "title": "write docs", "done": False}}

@app.get("/api/todos")
def list_todos():
    done = request.args.get("done")
    items = list(TODOS.values())
    if done is not None:
        items = [t for t in items if t["done"] == (done == "true")]
    return {"items": items, "count": len(items)}

@app.post("/api/todos")
def create_todo():
    data = request.get_json(silent=True) or {}
    if not isinstance(data.get("title"), str) or not data["title"].strip():
        return {"error": "title is required"}, 422
    todo = {"id": max(TODOS) + 1, "title": data["title"].strip(), "done": False}
    TODOS[todo["id"]] = todo
    return todo, 201, {"Location": f"/api/todos/{todo['id']}"}

@app.patch("/api/todos/<int:todo_id>")
def update_todo(todo_id):
    todo = TODOS.get(todo_id) or abort(404)
    todo.update({k: v for k, v in (request.get_json() or {}).items() if k in ("title", "done")})
    return todoPOST /api/todos -> 422 UNPROCESSABLE ENTITY
  {"error": "title is required"}
POST /api/todos -> 201 CREATED
  {"done": false, "id": 2, "title": "ship it"}
PATCH /api/todos/2 -> 200 OK
  {"done": true, "id": 2, "title": "ship it"}
GET /api/todos?done=true -> 200 OK
  {"count": 1, "items": [{"done": true, "id": 2, "title": "ship it"}]}

Class-based views with MethodView

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)

class ItemAPI(MethodView):
    def get(self, item_id):
        return {"id": item_id}

    def delete(self, item_id):
        return "", 204

app.add_url_rule("/items/<int:item_id>", view_func=ItemAPI.as_view("item"))GET /items/3 -> 200 OK
  {"id": 3}
DELETE /items/3 -> 204 NO CONTENT
PUT /items/3 -> 405 METHOD NOT ALLOWED
  (HTML page: 405 Method Not Allowed)

Allow requests from another origin

Flask-CORS adds the Access-Control headers browsers need for cross-origin calls. List exact origins; * with credentials does not work and is rarely what you want.

from flask_cors import CORS

CORS(app, resources={r"/api/*": {"origins": ["https://app.example.com"]}})

CLI Commands

The flask command

Built-in commands

CommandDoes
flask --app app run --debugDevelopment server with reloader and debugger
flask --app app routesList every route with its methods and endpoint
flask --app app shellPython shell with the app context pushed
flask --app app --helpEvery command, including the ones extensions add

Add your own command

Commands run with the app context pushed, so they can use the database. Run it as flask --app app seed --count 2.

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("seed")
@click.option("--count", default=3, help="How many users to create.")
def seed(count):
    """Create test users."""
    for i in range(count):
        click.echo(f"created user{i}")

runner = app.test_cli_runner()
print(runner.invoke(args=["seed", "--count", "2"]).output, end="")created user0
created user1

Testing

Test with pytest

Fixtures in conftest.py

tests/conftest.py
import pytest
from shop import create_app

@pytest.fixture
def app():
    app = create_app({"TESTING": True, "SECRET_KEY": "test"})
    yield app

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

Write tests

resp.json parses the body, and client.post(..., json=...) sets the Content-Type for you. With TESTING on, exceptions in views reach the test instead of becoming a 500 page.

tests/test_health.py
def test_health(client):
    resp = client.get("/health")
    assert resp.status_code == 200
    assert resp.json == {"status": "ok"}

def test_login_required(client):
    assert client.get("/account").status_code == 401

def test_post_json(client):
    resp = client.post("/api/todos", json={"title": "x"})
    assert resp.status_code == 201
    assert resp.headers["Location"].startswith("/api/todos/")

Set up session data in a test

session_transaction edits the session cookie the test client sends next. test_request_context lets you call code that reads request without sending a request.

from flask import Flask, session

app = Flask(__name__)
app.secret_key = "test"

@app.get("/me")
def me():
    return {"user": session.get("user_id")}

client = app.test_client()
with client.session_transaction() as s:
    s["user_id"] = 7
print(client.get("/me").json)

with app.test_request_context("/search?q=flask"):
    from flask import request
    print(request.args["q"], request.path){'user': 7}
flask /search

Run the tests

$ pip install pytest pytest-cov
$ pytest -q
$ pytest --cov=shop --cov-report=term-missing

Static Files & Uploads

Static files

Link to files in static/

Flask serves the static folder at /static in development. In production let the web server or a CDN serve it.

<link rel="stylesheet" href="{{ url_for('static', filename='css/app.css') }}">
<script src="{{ url_for('static', filename='js/app.js') }}" defer></script>

Uploads

Accept an upload safely

secure_filename strips path parts and unsafe characters. MAX_CONTENT_LENGTH makes Flask reject bigger bodies with 413 before your code runs.

from pathlib import Path
from flask import Flask, request, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024
UPLOADS = Path("uploads")
ALLOWED = {".png", ".jpg", ".pdf"}

@app.post("/upload")
def upload():
    f = request.files.get("file")
    if not f or not f.filename:
        abort(400)
    name = secure_filename(f.filename)
    if Path(name).suffix.lower() not in ALLOWED:
        abort(415)
    UPLOADS.mkdir(exist_ok=True)
    f.save(UPLOADS / name)
    return {"saved": name}, 201

print(secure_filename("../../etc/passwd"), secure_filename("my report (final).pdf"))etc_passwd my_report_final.pdf
POST /upload -> 201 CREATED
  {"saved": "Q3_report.pdf"}
POST /upload -> 415 UNSUPPORTED MEDIA TYPE
  (HTML page: 415 Unsupported Media Type)
POST /upload -> 413 REQUEST ENTITY TOO LARGE
  (HTML page: 413 Request Entity Too Large)

Deployment

Run in production

Gunicorn on Linux, Waitress on Windows

A common starting point for Gunicorn workers is two per CPU core plus one. Put Nginx, Caddy or a load balancer in front for HTTPS and static files.

$ pip install gunicorn
$ gunicorn -w 4 -b 127.0.0.1:8000 "shop:create_app()"
$ pip install waitress
$ waitress-serve --listen=127.0.0.1:8000 --call shop:create_app

Behind a reverse proxy

ProxyFix trusts the X-Forwarded-* headers from one proxy, so request.remote_addr, url_for(_external=True) and redirects use the real client IP and https. Only set the counts to the number of proxies you actually have.

from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)

A minimal Dockerfile

Dockerfile
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt gunicorn
COPY . .
USER nobody
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "shop:create_app()"]

Popular Extensions

Extensions worth knowing

What to add for each job

Check each extension's last release and its support for Flask 3.1 before adding it; several older extensions are no longer maintained.

ExtensionFor
Flask-SQLAlchemySQLAlchemy models and sessions bound to the app
Flask-MigrateAlembic database migrations
Flask-LoginUser sessions, login_required, remember me
Flask-WTFForms with CSRF protection
Flask-CORSCross-origin headers for APIs
Flask-CachingCaching views and functions in Redis, Memcached or memory
Flask-LimiterRate limits per route or per user
Flask-MailSending email
Flask-SmorestOpenAPI documented REST APIs with marshmallow
Flask-TalismanHTTPS redirects and security headers
Flask-SessionServer-side sessions in Redis or a database

Security Checklist

Before going live

The checklist

CheckHow
Debug offNever run with --debug or DEBUG=True in production; the debugger can run code
Strong secretSECRET_KEY from the environment, at least 32 random bytes: python -c "import secrets; print(secrets.token_hex(32))"
HTTPS cookiesSESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True (the default), SESSION_COOKIE_SAMESITE="Lax"
CSRFFlask-WTF's CSRFProtect for forms that use cookies
EscapingLeave Jinja autoescape on; avoid `safe` on user input
SQLUse SQLAlchemy queries or bound parameters, never f-strings in SQL
UploadsMAX_CONTENT_LENGTH, secure_filename and an extension allow-list
HostsTRUSTED_HOSTS or your proxy's host check (3.1)
HeadersContent-Security-Policy, X-Content-Type-Options, frame-ancestors, for example with Flask-Talisman

Errors & Gotchas

Error messages

What the common errors mean

ErrorUsually means
RuntimeError: Working outside of application contextCode used current_app, g or the database outside a request or app.app_context()
RuntimeError: The session is unavailable because no secret key was setSet SECRET_KEY before using session or flash
werkzeug.routing.exceptions.BuildErrorurl_for got a wrong endpoint name or a missing variable; blueprints need the prefix, as in orders.index
jinja2.exceptions.TemplateNotFoundThe template is not in a templates folder next to the app or blueprint
405 Method Not AllowedThe route does not list that method in methods
400 Bad RequestA missing key in request.form or request.args[...]; use .get()
415 Unsupported Media Typeget_json() on a request without a JSON Content-Type
ImportError with partially initialized moduleA circular import; move imports into create_app

Flask 2.3 to 3.1

Release history

Recent versions

Check the installed version with flask --version, or importlib.metadata.version("flask") in code, since flask.__version__ is deprecated.

VersionReleasedChanges
3.1.3February 18, 2026Security fix: the session is marked as accessed for key-only operations such as in
3.1.1May 13, 2025Security fix for the signing key order with SECRET_KEY_FALLBACKS
3.1.0November 13, 2024Python 3.9+, SECRET_KEY_FALLBACKS, TRUSTED_HOSTS, MAX_FORM_MEMORY_SIZE, MAX_FORM_PARTS, partitioned cookies
3.0.0September 30, 2023Removed deprecated code, needs Werkzeug 3; flask.__version__ deprecated
2.3.0April 25, 2023Python 3.8+, removed FLASK_ENV, before_first_request and the JSON_* config keys; import Markup from markupsafe

What Is a Flask Cheat Sheet

A Flask cheat sheet is a quick reference to the routes, request and response objects, template syntax, configuration and extensions of Flask, the Python web framework, arranged so you can find how to read a query parameter, return JSON or register a blueprint in seconds. People also search for a Flask quick reference or Flask Python cheat sheet; they usually need it while building an API, adding a feature to an existing app or moving a prototype to production.

This one has 23 sections and 65 rows, written for Flask 3.1. Every example with an output is a complete app that was run through Flask's test client with Flask 3.1.3, Werkzeug 3.1.9 and Python 3.14, so the status codes, headers and bodies under the code are real responses, not descriptions of what should happen. Database examples use Flask-SQLAlchemy 3.1 in the SQLAlchemy 2.x style.

How It Differs From the Flask Docs

The official tutorial and API reference are well written and long. This page skips the explanations of why Flask is designed the way it is and gives you the code for each task, with the response it produces and the gotcha that usually trips people up, such as the trailing slash redirect, the 400 from a missing form key or the error from code that runs outside the application context.


What This Flask Cheat Sheet Covers


Flask Quick Reference

TaskFlask
Create the appapp = Flask(__name__)
Route@app.route("/path")
GET or POST only@app.get("/x"), @app.post("/x")
URL variable"/users/<int:user_id>"
Query parameterrequest.args.get("q")
Form fieldrequest.form.get("email")
JSON bodyrequest.get_json()
Return JSONreturn {"ok": True}
Status codereturn body, 201
Redirectreturn redirect(url_for("index"))
Errorabort(404)
Templaterender_template("page.html", x=1)
Session valuesession["user_id"] = 7
Per-request storageg.user
Config valueapp.config["SECRET_KEY"]
BlueprintBlueprint("orders", __name__, url_prefix="/orders")
Run in developmentflask --app app run --debug
List routesflask --app app routes
Test requestapp.test_client().get("/")

What Flask Is

Flask is a WSGI web framework for Python, started by Armin Ronacher in 2010 and maintained by the Pallets community together with the libraries it is built on: Werkzeug for HTTP and routing, Jinja for templates, Click for the command line and ItsDangerous for signed cookies. It calls itself a microframework because the core stays small and makes few decisions for you: there is no built-in database layer, form library or admin site, and you add what you need through extensions. The official Flask documentation covers each part in depth.

That small core is why Flask is a common choice for back-end development in Python teams: JSON APIs, internal dashboards, machine learning model servers and services that need to start small. It also appears in lists of apps built with Python at companies that later grew far beyond the first prototype.

How a Request Flows Through Flask

A WSGI server such as Gunicorn receives the HTTP request and hands it to the Flask app. Flask pushes an application context and a request context, runs any before_request functions, matches the URL against the routing rules, calls the view function with the converted URL variables, turns its return value into a Response, runs after_request functions and sends the response back. Understanding these contexts explains most Flask error messages, which is why they have their own section on this page.


Flask, Django and FastAPI Compared

FlaskDjangoFastAPI
StyleMicroframeworkFull-stack frameworkAPI framework
Server interfaceWSGI, async views supportedWSGI and ASGIASGI
DatabaseYour choice, often Flask-SQLAlchemyBuilt-in ORMYour choice, often SQLAlchemy or SQLModel
Admin siteExtensionBuilt inExtension
Request validationManual or an extensionForms and serializersBuilt in with Pydantic
Best forAPIs, services, small to medium appsLarge database-driven sitesTyped async APIs

If Flask does not fit, the Flask alternatives guide compares the other options, and the Django cheat sheet covers the full-stack route.


Common Flask Mistakes

  • Running the development server in production. It is single-process and the debugger can run code; use Gunicorn or Waitress.
  • A hard-coded SECRET_KEY in the repository. Anyone with the key can forge session cookies. Load it from the environment.
  • Indexing request.form or request.args. A missing key becomes a 400 error; use .get() with a default.
  • Mutating a list in the session without assigning it back. Flask does not notice the change and the cookie is not updated.
  • Circular imports between app.py and blueprints. Use an application factory and import blueprints inside it.
  • Using |safe on user input. It turns off escaping and opens the page to cross-site scripting.
  • Forgetting the app context in scripts. Database code outside a request needs with app.app_context():.

How to Learn Flask Well

Start With One File

Write a single app.py with a few routes, a template and a JSON endpoint, and test each one with the test client, as the examples on this page do. Get comfortable with request, responses, url_for and templates before adding any extension. If Python itself is new, keep the Python cheat sheet open next to this one.

Then Structure It

Move to an application factory with blueprints as soon as the file passes a few hundred lines, add Flask-SQLAlchemy and Flask-Migrate for data, and write pytest tests with fixtures. Before your first app deployment, go through the security checklist and run the app under Gunicorn locally. For the API design side, the REST API cheat sheet and the HTTP status codes cheat sheet cover methods, status codes and error formats.


How This Flask Cheat Sheet Is Maintained

Each example with output is a complete program. A build script extracts it from the page, runs it with Flask 3.1.3, Werkzeug 3.1.9, Flask-SQLAlchemy 3.1.1, SQLAlchemy 2.1 and Flask-Login 0.6.3 on Python 3.14, sends the requests shown through the test client and writes the real responses under the code. Configuration defaults were read from a live Flask 3.1.3 app, and the release history from the Flask changelog.

Sources: the Flask 3.1 documentation and changelog, the Werkzeug routing documentation, the Flask-SQLAlchemy 3.1 and Flask-Login documentation, and the Jinja template designer documentation.


Flask Questions People Actually Ask

What is Flask used for?

Flask is a small Python web framework for building websites, JSON APIs and internal tools. It handles routing, requests, responses, templates and sessions, and leaves the database, forms and authentication to extensions you choose, which makes it popular for APIs, microservices and prototypes that may grow into full applications.

What is the latest version of Flask?

Flask 3.1.3, released on February 18, 2026, is the latest version. It is a security release in the 3.1 series, which needs Python 3.9 or newer and Werkzeug 3.1. Flask 3.1.0 added SECRET_KEY_FALLBACKS for key rotation, TRUSTED_HOSTS and new limits on form size.

How do I run a Flask app?

Install Flask in a virtual environment, then run flask --app app run --debug, where app is the name of your Python file. Debug mode reloads the server when code changes. In production, run the app with a WSGI server such as Gunicorn or Waitress instead of the development server.

How do I return JSON from Flask?

Return a dict or a list from the view and Flask converts it to a JSON response with the application/json content type. Return a tuple to add a status code or headers, for example return {"id": 9}, 201. jsonify still works and is useful when you need a Response object.

What is the difference between Flask and Django?

Flask is a microframework: it gives you routing, templates and sessions and lets you pick the rest. Django is a full-stack framework with an ORM, admin site, forms, authentication and migrations built in. Flask suits APIs and small to medium services; Django suits large, database-driven sites that benefit from its conventions.

What is a Flask blueprint?

A blueprint is a group of routes, templates and static files that you register on an app, usually with a URL prefix such as /orders. Blueprints split a large app into modules and let you reuse a feature in several apps. Endpoint names get the blueprint name as a prefix, as in url_for("orders.index").

How do I get request data in Flask?

Use request.args for the query string, request.form for form fields, request.get_json() for a JSON body, request.files for uploads and request.headers and request.cookies for the rest. Use .get() with a default, and type=int for numbers, to avoid a 400 error when a value is missing.

Is Flask good for production?

Yes. Flask runs large production services when it is served by a WSGI server such as Gunicorn or uWSGI behind a reverse proxy. Turn debug mode off, set a strong SECRET_KEY from the environment, secure the session cookie and add CSRF protection for forms that rely on cookies.

Is this Flask cheat sheet up to date?

Yes. It was checked on December 2, 2026 against Flask 3.1.3, Werkzeug 3.1.9, Flask-SQLAlchemy 3.1.1 with SQLAlchemy 2.1 and Flask-Login 0.6.3. The output under the examples was produced by running each one through Flask's test client.

Can I download this Flask cheat sheet as a PDF?

Yes. Use your browser's print command and choose Save as PDF. The print layout keeps every snippet, output and explanation and leaves out the search box, navigation and tools. Run a search first to print only the rows that are still visible.