Routing & requests
Decorate a function to make it a route. Path parameters are typed.
@app.get("/")
@app.post("/submit")
@app.route("/x", methods=("GET", "POST"))
@app.get("/user/<id:int>/posts/<slug>") class=com># converters: int, str, path, slug
class=kw>def show(req):
class=kw>return req.params["id"], req.params["slug"]
The Request object
req.method, req.path | basics |
req.query | query-string dict |
req.params | path parameters (typed) |
req.form | parsed application/x-www-form-urlencoded body |
req.json() | parsed JSON body |
req.header("X"), req.cookies | headers / cookies |
req.session | signed-cookie session (a dict) |
req.subject | who to bill: user / api-key / session |
req.user | current user (with auth) |
Responses
class=kw>return "plain html" class=com># str -> 200 text/html
class=kw>return {"a": 1} class=com># dict -> JSON
class=kw>return ("nope", 404) class=com># (body, status)
class=kw>return Response.json({"ok": True}, status=201)
class=kw>return Response.redirect("/login")
Blueprints
Group routes under a prefix:
class=kw>from larz class=kw>import Blueprint
api = Blueprint("api", prefix="/api/v1")
@api.get("/ping")
class=kw>def ping(req): class=kw>return "pong"
app.register(api)
Serve static files with
app.static("/static", "./static").
Add middleware with app.use(...) โ see Security.