- AsgiContext and AsgiWebSocket now default missing scope key to 'http' / 'ws' respectively (Daphne omits it for websocket scopes) - Add regression test for websocket scope without scheme - Update example/session.py WS handler to read the session; cookie must be set via HTTP first because common ASGI servers ignore the headers field on websocket.accept - Update README with the same caveat about Granian/Daphne/curl
36 lines
1.2 KiB
Python
36 lines
1.2 KiB
Python
from kaya.core import HttpContext, KayaApp, WebSocket
|
|
from kaya.session import InMemorySessionStore, SessionMixin
|
|
|
|
app = KayaApp(mixins=[SessionMixin(InMemorySessionStore())])
|
|
|
|
|
|
@app.GET('/')
|
|
async def home(ctx: HttpContext) -> None:
|
|
visits = ctx.session.get('visits', 0) + 1
|
|
ctx.session['visits'] = visits
|
|
await ctx.send_str(200, f'visits: {visits}')
|
|
|
|
|
|
@app.GET('/read')
|
|
async def read(ctx: HttpContext) -> None:
|
|
visits = ctx.session.get('visits', 0)
|
|
await ctx.send_str(200, f'visits: {visits}')
|
|
|
|
|
|
@app.GET('/clear')
|
|
async def clear(ctx: HttpContext) -> None:
|
|
ctx.session.invalidate()
|
|
await ctx.send_str(200, 'session cleared')
|
|
|
|
|
|
@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.
|
|
await ws.accept()
|
|
visits = ws.session.get('visits', 0)
|
|
await ws.send_text(f'visits: {visits}')
|