duck.http.middlewares.contrib.session

Session middleware for Duck.

The session cookie is established once on the initial HTTP handshake.

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.

… 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.

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

Notes:

  • If session is already set, either by Lively or other top-level middleware, this will do nothing.

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.