Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 72 ยท Practice and Review

Flask Cheat Sheet

A one-page Flask 3 cheat sheet with routing, request and response, Jinja, sessions, configuration, blueprints, SQLAlchemy, testing and deployment snippets.

This page packs the whole course into one place: the Flask calls, Jinja syntax and conventions you will use every day, in compact examples you can scan in seconds. Keep it open while you code, while working on the practice exercises, or right before an interview.

Each section links to the lesson that explains the topic. Three live editors at the end of the sections run real Flask code in your browser, so you can change a line and see what happens. The target is Flask 3.1; snippets that need an extension say so.

Setup and running

Terminal
python -m venv .venv                 # create a virtual environment
source .venv/bin/activate            # Windows: .venv\Scripts\activate
pip install flask                    # add flask-sqlalchemy, flask-login, ... as needed

flask --app app run --debug          # development server with reloader + debugger
flask --app app routes               # list all routes
flask --app app shell                # Python shell with app context
Python
from flask import Flask

app = Flask(__name__)

@app.get("/")
def index():
    return "Hello, Flask!"

Never run --debug in production. See Setup and Your First App and Project Layout.

Routing

Python
@app.route("/path")                          # GET (HEAD and OPTIONS automatic)
@app.route("/submit", methods=["GET", "POST"])
@app.get("/items")                           # shortcuts: get, post, put, patch, delete
@app.post("/items")

@app.get("/users/<int:user_id>")             # converter + variable
@app.get("/files/<path:subpath>")            # may contain slashes
@app.get("/tags/<slug>")                     # default converter: string, no slashes
Converter Matches Python type
string (default) text without / str
int digits (use signed=True for negatives) int
float decimals such as 3.5 float
path text including / str
uuid UUID strings uuid.UUID

A trailing slash in the rule (/docs/) redirects /docs to /docs/; without it, /docs/ is a 404. Wrong method on a known URL gives 405.

Python
url_for("index")                             # "/"
url_for("show_user", user_id=7)              # "/users/7"
url_for("show_user", user_id=7, tab="posts") # "/users/7?tab=posts"
url_for("static", filename="app.css")        # "/static/app.css"
url_for("index", _external=True)             # "http://host/"
url_for("blog.post", slug="hello")           # blueprint endpoint: "blueprint.function"

See Routes and HTTP Methods, URL Variables and Converters and url_for.

Request

Python
from flask import request

request.method                 # "GET", "POST", ...
request.args.get("q", "")      # query string  ?q=...
request.args.get("page", 1, type=int)
request.form.get("email")      # form body (urlencoded or multipart)
request.get_json(silent=True)  # JSON body, None if invalid / wrong type
request.files.get("avatar")    # FileStorage
request.headers.get("User-Agent")
request.cookies.get("theme")
request.path, request.url, request.remote_addr
request.is_json                # Content-Type says JSON

request.form["x"] raises a 400 when x is missing; .get("x") returns None. All of it is untrusted input. See The Request Object.

Response

Python
return "text"                              # 200, text/html
return {"ok": True}                        # JSON (dict or list)
return jsonify(items=items), 201           # JSON + status
return "created", 201, {"X-Id": "7"}       # body, status, headers
return "", 204                             # no content
return redirect(url_for("index"))          # 302
return redirect(url_for("index"), code=301)
abort(404)                                 # raise HTTP error

response = make_response(render_template("page.html"))
response.set_cookie("theme", "dark", max_age=3600, httponly=True, samesite="Lax")
response.headers["Cache-Control"] = "public, max-age=300"
return response
Status Use for
200 / 201 / 204 OK / created / done, nothing to return
301 / 302 / 303 / 308 permanent / temporary / see other / permanent, same method
400 / 401 / 403 / 404 bad input / not logged in / not allowed / missing
405 / 409 / 413 / 422 wrong method / conflict / too large / invalid values
429 / 500 too many requests / server bug

See Responses, Status Codes and Headers.

Errors

Python
from werkzeug.exceptions import HTTPException

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

@app.errorhandler(HTTPException)                 # every HTTP error
def http_error(error):
    return {"error": error.name}, error.code

@app.errorhandler(Exception)                     # unexpected exceptions
def crash(error):
    app.logger.exception("Unhandled error")
    return {"error": "internal error"}, 500

See Error Handling and Custom Error Pages.

Jinja templates

Syntax Meaning
{{ user.name }} output (escaped); dots reach attributes and keys
{{ price|round(2) }} apply a filter
{% if x %}...{% elif y %}...{% else %}...{% endif %} condition
{% for item in items %}...{% else %}empty{% endfor %} loop (else runs when empty)
loop.index, loop.first, loop.last loop variables (1-based index)
{% extends "base.html" %} / {% block body %}...{% endblock %} inheritance
{% include "partial.html" %} insert another template
{% macro field(name) %}...{% endmacro %} reusable snippet
{% set total = a + b %} variable
{# comment #} comment
{{ html|safe }} disable escaping (trusted HTML only)
{{- x -}} trim whitespace around the tag
Python
render_template("page.html", title="Home", items=items)   # templates/ folder
render_template_string("Hi {{ name }}", name="Ada")

@app.template_filter("money")
def money(cents):
    return f"${cents / 100:,.2f}"

@app.context_processor
def inject_site():
    return {"site_name": "My Site"}      # available in every template

Always available in templates: request, session, g, config, url_for, get_flashed_messages. See the Templates lessons, Template Inheritance and Filters and Tests.

Forms, cookies, sessions and flash

Python
app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]   # required for session and flash

session["user_id"] = 5          # set (signed cookie, readable by the client!)
session.get("user_id")          # read
session.pop("user_id", None)    # remove one
session.clear()                 # log out
session.permanent = True        # use PERMANENT_SESSION_LIFETIME

flash("Saved!", "success")      # message for the next request
get_flashed_messages(with_categories=True)   # in a template or view

Post/Redirect/Get: handle the POST, then return redirect(url_for(...)). Never trust a hidden field or cookie for permissions. See Handling HTML Forms, Cookies, Sessions and Flash Messages.

Configuration

Python
app.config["DEBUG"] = False
app.config.update(SECRET_KEY="...", MAX_CONTENT_LENGTH=2 * 1024 * 1024)
app.config.from_object("config.ProductionConfig")
app.config.from_prefixed_env()                 # FLASK_SECRET_KEY, FLASK_DEBUG, ...
app.config.from_pyfile("config.py", silent=True)   # instance folder
Key Purpose
SECRET_KEY signs sessions and tokens
TESTING exceptions propagate to the test client
MAX_CONTENT_LENGTH request size limit (413 when exceeded)
SESSION_COOKIE_SECURE / _HTTPONLY / _SAMESITE cookie flags
PERMANENT_SESSION_LIFETIME lifetime of permanent sessions
SQLALCHEMY_DATABASE_URI database URL (Flask-SQLAlchemy)

See Configuration and Environments.

Structure: factory, blueprints, hooks

Python
# app/__init__.py
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object("config.Default")
    if config:
        app.config.update(config)
    db.init_app(app)
    from .blog import bp as blog_bp
    app.register_blueprint(blog_bp, url_prefix="/blog")
    return app

# app/blog.py
bp = Blueprint("blog", __name__)

@bp.get("/")
def index(): ...                       # endpoint: "blog.index"
Python
@app.before_request        # runs before each request; return a response to short-circuit
@app.after_request         # def f(response): ...; return response
@app.teardown_request      # always runs at the end
@app.teardown_appcontext   # release resources (db connections)

from flask import g, current_app
g.user = ...               # per-request scratch space
current_app.config["X"]    # the active app (inside a context)
flowchart TD
    A["Where should this data live?"] --> B{"Needed only<br/>during this request?"}
    B -- yes --> C["g or a local variable"]
    B -- no --> D{"Per visitor and<br/>safe to expose?"}
    D -- yes --> E["session or a cookie"]
    D -- no --> F{"Shared by all users<br/>or must persist?"}
    F -- yes --> G["Database or Redis"]
    F -- no --> H["Server-side session<br/>store keyed by cookie id"]

Anything that must outlive the request or be shared between workers belongs in a database, not in Python memory.

See The Application Factory, Blueprints and Hooks, Application Context and g.

Databases

Python
# sqlite3 (standard library)
db = sqlite3.connect(path)
db.row_factory = sqlite3.Row
db.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()   # always placeholders
db.commit()
Python
# Flask-SQLAlchemy 3 (SQLAlchemy 2 style)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, selectinload

class Base(DeclarativeBase): pass
db = SQLAlchemy(model_class=Base)

class User(db.Model):
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(db.String(120), unique=True)
    posts: Mapped[list["Post"]] = relationship(back_populates="author")

db.session.add(user); db.session.commit()
db.session.get(User, 1)                                  # by primary key
db.get_or_404(User, 1)                                   # or 404
db.session.scalars(db.select(User).where(User.email == e)).first()
db.session.scalars(db.select(User).options(selectinload(User.posts))).all()   # avoid N+1
db.paginate(db.select(User).order_by(User.id), page=1, per_page=20)
db.session.delete(user); db.session.commit()
Terminal
flask db init            # Flask-Migrate: once
flask db migrate -m "add posts"
flask db upgrade         # apply;  flask db downgrade  to undo

See sqlite3 with Flask, Flask-SQLAlchemy Models, Queries and CRUD, Relationships and Migrations.

Authentication and security

Python
from werkzeug.security import generate_password_hash, check_password_hash

hash_ = generate_password_hash(password)          # salted, slow hash
check_password_hash(hash_, attempt)               # True / False

def login_required(view):
    @wraps(view)
    def wrapper(*args, **kwargs):
        if "user_id" not in session:
            return redirect(url_for("login", next=request.path))
        return view(*args, **kwargs)
    return wrapper
  • Same error message for unknown user and wrong password; session.clear() on login.
  • CSRF token on every POST form (Flask-WTF CSRFProtect), SameSite=Lax cookies.
  • Autoescaping on; never |safe user input. Parameterized SQL only.
  • Redirect only to local paths after login (next starts with a single /).
  • Set Secure, HttpOnly cookie flags and serve over HTTPS.

See Password Hashing, Building a Login System, Flask-Login, Roles and Permissions and Web Security Essentials.

JSON APIs

Python
@app.post("/api/items")
def create_item():
    data = request.get_json(silent=True) or {}
    if not data.get("name"):
        return {"error": "name is required"}, 400
    item = save(data)
    return item, 201, {"Location": url_for("get_item", item_id=item["id"])}

GET read, POST create, PUT replace, PATCH change part, DELETE remove. PUT and DELETE are idempotent. Use MethodView classes for resource-style APIs and itsdangerous or JWT for tokens. See Building JSON APIs, Designing a REST API and API Authentication.

Live reference: the basics in one run

This editor exercises routing, a query string, URL variables, redirects, cookies, the session, flash messages and an error handler. Change a route and rerun it.

Python Core Flask features in one app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The flash messages appear once and are gone on the next read, which is why the second /messages call is empty.

Live reference: Flask-SQLAlchemy in a minute

Python Models, queries, joins and pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Testing and CLI

Python
client = app.test_client()
client.get("/path?x=1")                     # or query_string={"x": 1}
client.post("/path", data={"a": "1"})       # form
client.post("/path", json={"a": 1})         # JSON
client.get("/p", headers={"Authorization": "Bearer token"})
client.get("/p", follow_redirects=True)
response.status_code, response.headers, response.get_json(), response.get_data(as_text=True)

with client.session_transaction() as sess:  # prepare a logged-in session
    sess["user_id"] = 1

with app.test_request_context("/x?y=1"):    # a request context without a request
    ...
runner = app.test_cli_runner()
runner.invoke(args=["init-db"])

pytest fixtures: build the app through the factory with {"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:"} and yield the client. See Testing Flask Apps with pytest.

Python Test client, session_transaction and CLI runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Deployment snippets

Terminal
pip install gunicorn
gunicorn -w 4 -b 127.0.0.1:8000 "app:create_app()"     # factory call syntax
Python
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)   # behind one proxy

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

Put nginx (or another reverse proxy) in front for TLS, static files and buffering; load secrets from the environment; run migrations as a deploy step. See Deployment and Logging and Debugging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line safely reads an optional query parameter as an integer with a default?

    args.get with type=int returns the default when the key is missing or not a valid integer, and never raises a 400.
  2. 2. What does a route declared as @app.route("/docs/") do when a visitor requests /docs?

    A rule with a trailing slash acts like a directory: the version without the slash is redirected to it. A rule without a slash does the opposite and returns 404 for the slash version.
  3. 3. Where is a Flask session stored by default?

    The data lives in the cookie, signed with SECRET_KEY. It cannot be changed without detection but it can be read, so keep secrets out of it.
  4. 4. How do you avoid the N+1 query problem with SQLAlchemy relationships?

    Eager loading fetches the related rows in a constant number of queries instead of one per parent.
  5. 5. Which tool lets you log in a test client without going through the login form?

    Inside session_transaction() you can write directly to the session that the client will send with its next requests.

Summary

  • Routes map URLs to functions; converters validate variables, url_for builds URLs from endpoint names, and Flask answers 404/405 for mismatches.
  • Read input from request.args, form, get_json(), files, headers and cookies; return strings, dicts, tuples or make_response objects.
  • Use autoescaped Jinja templates with inheritance, filters and context processors; keep the session small, signed and non-secret.
  • Structure bigger apps with a factory, blueprints, request hooks and environment-based configuration.
  • Use parameterized SQL or SQLAlchemy, eager loading and migrations; hash passwords, protect forms with CSRF tokens, redirect only to local paths.
  • Test with test_client, session_transaction, test_request_context and test_cli_runner; deploy with a WSGI server behind a reverse proxy.

That completes the reference. To revisit the theory, start again from What Is Flask?, or practice by building the blog project.