Flask Cheat Sheet
Free Flask cheat sheet: the most-used Flask syntax and methods at a glance — searchable and beginner-friendly.
Setup & Routes
| Concept | Syntax | Example |
|---|---|---|
| Create the app __name__ helps Flask locate templates and static files. | app = Flask(__name__) | from flask import Flask
app = Flask(__name__) |
| Basic route The function returns the response body for that URL. | @app.route("/") | @app.route("/")
def home():
return "Hello" |
| HTTP methods Routes default to GET only; list every method you allow. | @app.route("/p", methods=["GET", "POST"]) | @app.route("/login", methods=["GET", "POST"])
def login():
... |
| URL parameters Use <int:..>, <float:..>, <path:..> converters to type the value. | @app.route("/user/<name>") | @app.route("/user/<int:uid>")
def profile(uid):
return str(uid) |
| Run the server debug=True enables auto-reload and the in-browser debugger. | app.run(debug=True) | if __name__ == "__main__":
app.run(debug=True) |
| URL building Generates URLs from view names so links survive route changes. | url_for("endpoint") | url_for("profile", uid=7) |
Request & Response
| Concept | Syntax | Example |
|---|---|---|
| Query string args Reads ?q=... values; the second arg is a default. | request.args.get("key") | q = request.args.get("q", "") |
| Form data Reads POSTed form fields submitted with the request. | request.form["field"] | name = request.form.get("name") |
| JSON body Parses an incoming JSON request body into a dict. | request.get_json() | data = request.get_json() |
| Redirect Send the browser to another route, typically after a POST. | redirect(url_for("home")) | return redirect(url_for("home")) |
| Set status & headers Return a tuple to control the HTTP status code and headers. | return body, status, headers | return "Not found", 404 |
| Abort with error Immediately stop and return an HTTP error response. | abort(code) | from flask import abort
abort(403) |
Templates (Jinja2)
| Concept | Syntax | Example |
|---|---|---|
| Render a template Looks in the templates/ folder; pass variables as keywords. | render_template("page.html", **ctx) | return render_template("index.html", user=user) |
| Output a variable Double braces print an expression, auto-escaped for safety. | {{ variable }} | <h1>Hello {{ name }}</h1> |
| Conditionals Statement blocks use {% %} and must be closed. | {% if cond %} ... {% endif %} | {% if user %}Hi {{ user }}{% else %}Guest{% endif %} |
| Loops Iterate over any iterable passed from the view. | {% for x in items %} ... {% endfor %} | {% for item in items %}<li>{{ item }}</li>{% endfor %} |
| Template inheritance Child templates fill named {% block %} sections of a layout. | {% extends "base.html" %} | {% extends "base.html" %}
{% block body %}...{% endblock %} |
| Static files Serves files from the static/ folder. | url_for("static", filename=...) | <link href="{{ url_for('static', filename='app.css') }}"> |
Forms & Sessions
| Concept | Syntax | Example |
|---|---|---|
| Secret key Required to sign session cookies; keep it secret in production. | app.secret_key = "..." | app.secret_key = "change-me" |
| Read/write session A signed cookie storing per-visitor data across requests. | session["key"] | session["user_id"] = user.id |
| Clear session Remove a value, e.g. to log a user out. | session.pop("key", None) | session.pop("user_id", None) |
| Flash messages Queue a one-time message to show on the next page. | flash("message") | flash("Saved!", "success") |
| Read flashes Pull queued flash messages inside a template. | get_flashed_messages() | {% for m in get_flashed_messages() %}{{ m }}{% endfor %} |
| Validate input Flask-WTF adds full form classes with built-in validation. | if not request.form.get(...): | if not request.form.get("email"):
flash("Email required") |
Database (SQLAlchemy)
| Concept | Syntax | Example |
|---|---|---|
| Configure The connection string for Flask-SQLAlchemy. | SQLALCHEMY_DATABASE_URI | app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db" |
| Init extension db gives you the Model base class and a session. | db = SQLAlchemy(app) | from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app) |
| Define a model Each class maps to a table, each Column to a field. | class User(db.Model): | class User(db.Model):
id = db.Column(db.Integer, primary_key=True) |
| Create tables Builds tables from your models; run once at setup. | db.create_all() | with app.app_context():
db.create_all() |
| Insert a row add() stages the object; commit() writes it to the DB. | db.session.add(obj); db.session.commit() | db.session.add(User(name="Ada"))
db.session.commit() |
| Query .all() returns a list, .first() one row or None. | Model.query.filter_by(...).all() | User.query.filter_by(name="Ada").first() |
REST & JSON
| Concept | Syntax | Example |
|---|---|---|
| Return JSON Serializes a dict/list and sets the JSON content type. | jsonify(data) | return jsonify({"ok": True, "items": items}) |
| JSON + status Pair the body with an explicit HTTP status code. | return jsonify(...), code | return jsonify(error="not found"), 404 |
| Blueprint Group related routes into a reusable module. | bp = Blueprint("api", __name__) | bp = Blueprint("api", __name__, url_prefix="/api") |
| Register blueprint Attach a blueprint's routes to the main app. | app.register_blueprint(bp) | app.register_blueprint(bp) |
| Restful resource Map GET/POST/PUT/DELETE to create/read/update/delete. | methods per verb | @app.route("/items/<int:id>", methods=["DELETE"])
def remove(id):
... |
| Error handler Return consistent JSON for error responses. | @app.errorhandler(code) | @app.errorhandler(404)
def not_found(e):
return jsonify(error="missing"), 404 |