Add websocket session support to kaya-session

- kaya-core: WebSocket ABC gains session attribute and accept(headers=...)
- kaya-core: AsgiWebSocket injects headers into websocket.accept message
- kaya-rsgi: RsgiWebSocket accepts headers param (ignored — Granian's
  accept() takes no args)
- kaya-session: SessionWebSocket wrapper exposes ws.session and injects
  Set-Cookie on accept()
- kaya-session: SessionMixin registers before/after websocket hooks;
  session loaded at connect, persisted on close if modified
- 10 new WV session tests covering read, persist, handshake cookie,
  regenerate, invalidate, isolation
- Example and README updated
This commit is contained in:
2026-07-23 22:11:04 +08:00
parent 65f1b79ce8
commit e4e00762bb
8 changed files with 390 additions and 37 deletions
+3 -7
View File
@@ -1,4 +1,4 @@
from kaya.core import HttpContext, KayaApp
from kaya.core import HttpContext, KayaApp, WebSocket
from kaya.session import InMemorySessionStore, SessionMixin
app = KayaApp(mixins=[SessionMixin(InMemorySessionStore())])
@@ -35,11 +35,7 @@ async def echo(ws: WebSocket) -> None:
@app.websocket('/ws/visits')
async def ws_visits(ws: WebSocket) -> None:
# WebSocket handlers can read the existing session. Most ASGI servers
# (including Granian and Daphne) do not forward the `headers` field of the
# `websocket.accept` message into the HTTP 101 response, so a new session
# cookie cannot be set during the handshake. Use the HTTP `/` endpoint to
# set or refresh the session cookie before connecting here.
visits = ws.session.get('visits', 0) + 1
ws.session['visits'] = visits
await ws.accept()
visits = ws.session.get('visits', 0)
await ws.send_text(f'visits: {visits}')