Skip to main content
Quick Reference

Flask Cheatsheet

Flask 3 on one page — the app and CLI, routes, the request object, Jinja templates, blueprints, config and sessions, SQLite, errors, the test client, and the traps that show up in interviews.

10 sections 10 tables 16 code snippets

App & the CLI

Smallest app

from flask import Flask

app = Flask(__name__)

@app.get("/")
def home():
    return {"ok": True}

Run it locally

python -m venv .venv
pip install flask
flask --app shop run --debug
# http://127.0.0.1:5000

What Flask is

PieceRole
Flask(__name__)The application object. __name__ finds templates and static files
flask --app shopshop.py is the module. Use shop:create_app for a factory
--debugReloads on save and shows the interactive debugger. Local only
A returned dictSent as JSON. You do not need jsonify for that
No ORM, no adminThose are other libraries. Flask is the request layer

This page is Flask 3. The development server is not the process you deploy. A public site uses a WSGI server such as Gunicorn or Waitress.

Routes

Methods and a converter

@app.get("/books")
def book_list():
    return render_template("books/list.html")

@app.get("/books/<int:book_id>")
def book_detail(book_id):
    return {"id": book_id}

@app.post("/books")
def book_create():
    return {"created": True}, 201

Routing rules

FormMeaning
@app.get / @app.postOne method. A POST to a GET route is 405
<int:book_id>The segment must be an integer, or the route is a 404
<string:title>Text without a slash. path may include slashes. Also float and uuid
url_for("book_detail", book_id=3)Build a path from the function name, not from a hard-coded string
Trailing slashA rule /books/ redirects /books to it. A rule /books does not accept the slash

Request & response

Read the incoming request

@app.post("/books")
def book_create():
    data = request.get_json(silent=True) or {}
    title = data.get("title", "")
    return {"title": title}, 201

A form field

@app.post("/search")
def search():
    q = request.form.get("q", "")
    return redirect(url_for("book_list", q=q))

Where the value lives

AttributeSource
request.argsThe query string. request.args.get("q", "")
request.formA posted HTML form
request.get_json()A JSON body. silent=True returns None instead of raising on a bad type
return body, 201Body plus status. A third item can be headers
redirect(url_for(...))After a successful POST, so a refresh does not submit again
abort(404)Stop the view and run the error handler

Jinja templates

Render

@app.get("/books")
def book_list():
    books = [{"title": "Flask"}]
    return render_template("books/list.html", books=books)

The template

{% extends "base.html" %}
{% block content %}
<ul>
  {% for book in books %}
    <li>{{ book.title }}</li>
  {% else %}
    <li>No books yet</li>
  {% endfor %}
</ul>
{% endblock %}

Template pieces

FormMeaning
templates/Next to the module, or inside the package
{{ book.title }}Print a value. HTML is escaped
{% for %} / {% else %}The else on a loop runs when the list is empty
{{ url_for("book_list") }}A path. For a file, url_for("static", filename="app.css")
|safeMarks a string as HTML. Only for markup you wrote

Blueprints

A feature module

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

@bp.get("/")
def book_list():
    return render_template("books/list.html")

def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    return app

Names

NameUse
Blueprint("books", ...)The first argument is the endpoint prefix
url_for("books.book_list")Blueprint name, a dot, then the function name
url_prefix="/books"Every route on this blueprint starts with /books
register_blueprintAn unregistered blueprint is invisible. Its routes 404
current_appThe app that is handling this request. Use it inside a blueprint, not a global app

A blueprint is a set of routes you can mount. It is not a Django app: there is no model registry and no automatic admin.

Config & sessions

Read secrets from the environment

app = Flask(__name__)
app.config.from_mapping(
    SECRET_KEY=os.environ["SECRET_KEY"],
)

A login flag

@app.post("/login")
def login():
    session["user_id"] = 7
    return redirect(url_for("home"))

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

Config keys

KeyEffect
SECRET_KEYSigns the session cookie. Without it, session cannot be saved
DEBUGThe interactive debugger. Never turn it on for a host other people can reach
TESTINGUsed by the test client. Exceptions propagate instead of becoming a 500 page
sessionA signed cookie dict. It is not the server-side user record
gStorage for this request only. It is empty again on the next request

SQLite

One connection per request

def get_db():
    if "db" not in g:
        g.db = sqlite3.connect(current_app.config["DATABASE"])
        g.db.row_factory = sqlite3.Row
    return g.db

@app.teardown_appcontext
def close_db(exc):
    db = g.pop("db", None)
    if db is not None:
        db.close()

A placeholder, not string building

row = get_db().execute(
    "SELECT id, title FROM book WHERE id = ?",
    (book_id,),
).fetchone()

Query habits

HabitWhy
? and a tupleThe driver binds the value. An f-string in SQL is an injection bug
sqlite3.RowColumns by name: row["title"]
gReuse one connection for the rest of this request
teardown_appcontextCloses the connection even when the view raised
commit()A write is not stored until you commit

Flask does not migrate tables for you. Create the schema yourself, or add a library such as Flask-SQLAlchemy and Alembic when the schema starts changing.

Errors

A missing page

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

@app.get("/books/<int:book_id>")
def book_detail(book_id):
    row = find_book(book_id)
    if row is None:
        abort(404)
    return {"id": row["id"], "title": row["title"]}

Status you will see

StatusUsual cause
404No route matched, a converter failed, or you called abort(404)
405The path exists, but not for this method
500An exception left the view and nothing handled it
400You rejected the body. Return it yourself when JSON is missing a field

The handler must return the status again. render_template(...) alone is 200, even inside a 404 handler.

The test client

Call a route without a socket

def test_home():
    app.config["TESTING"] = True
    client = app.test_client()
    response = client.get("/")
    assert response.status_code == 200
    assert response.get_json()["ok"] is True

What the client does

CallEffect
app.test_client()A fake browser aimed at this app
client.get / client.postRuns the view. json= sends a JSON body
response.get_json()Parses a JSON response
TESTING = TrueLets the exception reach the test instead of a debugger page
A factoryBuild a fresh app in the test so config from another test does not leak

Interview traps

Traps worth memorising

TrapWhat happensPrefer
--debug on a public hostThe debugger can run code for anyone who can reach itDebug only on your machine
No SECRET_KEYSaving session raisesA long random value from the environment
url_for("book_list") on a blueprintThe endpoint is not foundurl_for("books.book_list")
Blueprint never registeredEvery one of its routes is a 404app.register_blueprint(bp)
f-string inside SQLA title can change the queryA ? placeholder and a tuple
404 handler without , 404The missing page is sent as 200Return the template and the status
POST to a @app.get route405 Method Not AllowedA @app.post view, then redirect
/books/ vs /booksOne of them 404s, or Flask redirectsPick one slash style and link with url_for
{{ title|safe }} on user textStored HTML runs in the page{{ title }}
Using g as a cache across requestsIt is empty on the next requestA database, or session for a signed cookie
request.form["title"]A missing field becomes a 400request.form.get("title", "")
app.run() in the deployed processThe development server is single-threaded and insecureGunicorn or Waitress

Bind the value

db.execute(
    "INSERT INTO book (title) VALUES (?)",
    (title,),
)
db.commit()

Redirect after a write

return redirect(url_for("books.book_list"))

How to use this page: put the smallest app in shop.py, run flask --app shop run --debug, and open the JSON home page. Then add one blueprint, one template, and a test that uses app.test_client().