Skip to content

Middleware

Middleware are callables (functions, classes) that works with every request before it is processed by views. And also with every response before returning it.

  • Middleware takes each request that comes to applications
  • It can then do something to that request or run code
  • Then it passes the request to be processed by the rest of the application (by individual views)
  • Takes the response generated by the application
  • Can do something to that response or run code
  • Finally returns the response.

Background tasks run after middleware.

SessionMiddleware

Bases: SessionMiddleware

Used to manage sessions.

Example:

import air
from time import time

app = air.Air()
app.add_middleware(air.SessionMiddleware, secret_key="change-me")

@app.page
async def index(request: air.Request):
    if "first-visited" not in request.session:
        request.session["first-visited"] = time()
    return air.layouts.mvpcss(
        air.H1(request.session.get("first-visited")),
        air.P("Refresh the page and the timestamp won't change"),
        air.P(air.A("Reset the time stamp", href="/reset")),
    )

@app.page
async def reset(request: air.Request):
    request.session.pop("first-visited")
    return air.responses.RedirectResponse("/")