Fix Daphne ASGI compatibility and document WS handshake cookie limitation

- 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
This commit is contained in:
2026-07-23 22:11:06 +08:00
parent e4e00762bb
commit ca023580e4
4 changed files with 39 additions and 12 deletions
+2 -2
View File
@@ -83,7 +83,7 @@ class AsgiContext(HttpContext):
self.path = scope['path']
self.query_string = scope['query_string'].decode()
self.method = HttpMethod(scope['method'])
self.scheme = scope['scheme']
self.scheme = scope.get('scheme', 'http')
self.client = scope['client']
self.server = scope['server']
self.headers = decode_headers(scope['headers'])
@@ -168,7 +168,7 @@ class AsgiWebSocket(WebSocket):
self._send = send
self.path = scope['path']
self.query_string = scope['query_string'].decode()
self.scheme = scope['scheme']
self.scheme = scope.get('scheme', 'ws')
self.client = scope['client']
self.server = scope['server']
self.headers = decode_headers(scope['headers'])
@@ -131,3 +131,23 @@ class WebSocketTest(unittest.TestCase):
await ws.accept()
self.assertEqual(1, len(sent_messages))
self.assertEqual({'type': 'websocket.accept'}, sent_messages[0])
@async_test
async def test_websocket_scope_without_scheme(self):
# Daphne omits the optional `scheme` key from websocket scopes.
async def send(message):
pass
async def receive():
return {'type': 'websocket.connect'}
scope = {
'type': 'websocket',
'path': '/echo',
'query_string': b'',
'client': ('127.0.0.1', 12345),
'server': ('127.0.0.1', 80),
'headers': [],
}
ws = AsgiWebSocket(scope, receive, send)
self.assertEqual('ws', ws.scheme)