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 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
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. 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 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)) 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 %} 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 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. 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")) 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() 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. 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"]} The handler must return the status again. render_template(...) alone is 200, even inside a 404 handler. 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 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(). |