Ushka

ushka.http.websocket

WebSockets. A handler named websocket in routes/, or @app.websocket:

# routes/chat.py
async def websocket(ws):
    await ws.accept()
    async for text in ws.iter_text():        # Untrusted, like any client data
        await ws.send_text(f"echo: {text}")

The handshake is checked before your code runs: a browser on another site cannot open the socket (the cross-site WebSocket hijacking attack), and allowed_hosts applies. Everything the client sends is marked Untrusted.

In this module

class WebSocketDisconnectThe connection ended: the client left, or sent something unacceptable.
class WebSocketOne WebSocket connection. request gives headers, query, cookies and session.

class WebSocketDisconnect (Exception)

The connection ended: the client left, or sent something unacceptable.

class WebSocket

One WebSocket connection. request gives headers, query, cookies and session.

Methods

accept
close
receive_text
receive_bytes
receive_json
iter_textYields each text message until the client disconnects.
send_text
send_bytes
send_json

accept

async def accept(
    subprotocol: str | None = None,
    headers: dict[str, str] | None = None,
) -> None

close

async def close(code: int = 1000, reason: str = '') -> None

receive_text

async def receive_text() -> str

receive_bytes

async def receive_bytes() -> bytes

receive_json

async def receive_json() -> Any

iter_text

async def iter_text() -> AsyncIterator[str]

Yields each text message until the client disconnects.

send_text

async def send_text(data: str) -> None

send_bytes

async def send_bytes(data: bytes) -> None

send_json

async def send_json(data: Any) -> None