duck.http.middlewares.contrib.session

Session middleware for Duck — covers both HTTP request/response and Lively WebSocket events.

The session cookie is established once on the initial HTTP handshake. Lively events share that same request object, so they only need to persist any session mutations — no cookie header can be sent mid-WebSocket.

Module Contents

Classes

SessionMiddleware

Creates, loads, and persists user sessions across both HTTP and Lively events.

API

class duck.http.middlewares.contrib.session.SessionMiddleware[source]

Bases: duck.http.middlewares.BaseMiddleware

Creates, loads, and persists user sessions across both HTTP and Lively events.

HTTP flow: process_request — load or create the session from the cookie. process_response — if the session was modified, save it and set the Set-Cookie header for new or expired sessions.

Lively (WebSocket) flow: process_lively_event — called after each Lively component dispatch event. Saves the session if it was modified. No cookie header is written because the WS connection already shares the original HTTP session.

… admonition:: Notes

Duck is lazy — it does not save the session automatically. This middleware is the single place responsible for all persistence. Never call request.SESSION.save() manually in a view or component if you want the Set-Cookie header to be handled correctly.

debug_message: str

‘SessionMiddleware: Session Error’

Returns the session key from request COOKIE.

async classmethod process_lively_event(ws, request: duck.http.request.HttpRequest) None[source]

Persist a modified session after a Lively WebSocket event completes.

If the session is new (client has no cookie yet), the session key is pushed to the browser via document.cookie over the WebSocket — the only channel available once the HTTP handshake is done.

Parameters:
  • ws – The LivelyWebSocketView handling the current event.

  • request – The shared HTTP request.

classmethod process_request(request: duck.http.request.HttpRequest) int[source]

Load an existing session from the cookie, or create a fresh one.

Sets request.session_exists so process_response knows whether to send a Set-Cookie header.

Parameters:

request – The incoming HTTP request.

Returns:

cls.request_ok always — session errors are non-fatal.

Return type:

int

classmethod process_response(response, request)[source]

Persist a modified session and set the Set-Cookie header when needed.

The cookie is only written for new sessions or sessions that expired and were recreated. Existing sessions already have the cookie in the browser, so resending it is unnecessary.

Parameters:
  • response – The outgoing HTTP response object.

  • request – The corresponding HTTP request.