网页 综合 更新时间 2026-11-14 09:44:38

WebSockets - Starlette

自动蜘蛛 starlette.dev 正文约 2245 字
Starlette includes a WebSocket class that fulfils a similar role to the HTTP request, but that allows sending and receiving data on a websocket.
Signature: WebSocket(scope, receive, send)
WebSockets present a mapping interface, so you can use them in the same way as a scope.
For instance: websocket['path'] will return the ASGI path.
The websocket URL is accessed as websocket.url.
The property is actually a subclass of str, and also exposes all the components that can be parsed out of the URL.
For example: websocket.url.path, websocket.url.port, websocket.url.scheme.
Headers are exposed as an immutable, case-insensitive, multi-dict.
For example: websocket.headers['sec-websocket-version']
Query parameters are exposed as an immutable multi-dict.
For example: websocket.query_params['search']
Router path parameters are exposed as a dictionary interface.
For example: websocket.path_params['username']
JSON messages default to being sent over text data frames, from version 0.10.0 onwards. Use websocket.send_json(data, mode="binary") to send JSON over binary data frames.
May raise starlette.websockets.WebSocketDisconnect().
JSON messages default to being received over text data frames, from version 0.10.0 onwards. Use websocket.receive_json(data, mode="binary") to receive JSON over binary data frames.
Similar to receive_text, receive_bytes, and receive_json but returns an async iterator.
When starlette.websockets.WebSocketDisconnect is raised, the iterator will exit.
If you need to send or receive raw ASGI messages then you should use websocket.send() and websocket.receive() rather than using the raw send and receive callables. This will ensure that the websocket's state is kept correctly updated.
If you call websocket.close() before calling websocket.accept() then the server will automatically send a HTTP 403 error to the client.
If you want to send a different error response, you can use the websocket.send_denial_response() method. This will send the response and then close the connection.
This requires the ASGI server to support the WebSocket Denial Response extension. If it is not supported a RuntimeError will be raised.
In the context of Starlette, you can also use the HTTPException to achieve the same result.
访问原文 返回搜索 https://starlette.dev/./websockets/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。