Config & discovery
flask --app <module>:<name> routes
Pick the app variable explicitly
flask --app
"<module>:create_app('<arg>')"
run
Call an app factory with arguments
Arguments are parsed as Python literals.
FLASK_APP=<module>
Environment form of --app
pip install python-dotenv
Enable .env and .flaskenv loading
.flaskenv is for public values; keep .env out of git.
Routing
@app.route("/")
Bind a URL to a view
@app.route("/user/<name>")
Dynamic URL part
@app.route("/post/<int:id>")
Typed converter
Converters: string, int, float, path, uuid.
@app.route("/login", methods=["GET",
"POST"])
Accept more HTTP methods
Routes answer GET only by default; HEAD and OPTIONS are
automatic.
@app.post("/login")
Method shortcut decorator
Also get, put, delete, patch.
url_for("<endpoint>", id=1)
Build the URL for a view
Unknown keywords become query parameters.
url_for("static",
filename="<file>")
URL of a static file
Blueprint("<name>", __name__)
Group routes into a module
app.register_blueprint(<bp>,
url_prefix="/<p>")
Attach a blueprint
Responses
return "<p>Hi</p>"
String becomes a 200 HTML response
return {"a": 1}
Dict or list becomes JSON
return <body>, 404
Body plus status code
Also (body, status, headers).
redirect(url_for("<endpoint>"))
Redirect to another view
abort(404)
Stop with an HTTP error
resp.set_cookie("<name>",
"<value>")
Set a cookie on a response
@app.errorhandler(404)
Custom error page
Return the template and the status, e.g. return
render_template(...), 404.
Templates & state
render_template("<file>.html", x=1)
Render templates/<file>.html
{{ x }}
Print an escaped value in Jinja
{% extends "base.html" %}
Inherit a layout
app.secret_key = <bytes>
Key needed for sessions and flash
Generate one with python -c 'import secrets;
print(secrets.token_hex())'.
session["<key>"] = <value>
Per-user data in a signed cookie
flash("<msg>")
Message for the next request