Larz › WebSockets in Python

WebSockets, first-class

Real-time, bidirectional messaging with a clean async handler — and a built-in server that speaks the WebSocket protocol, no extra install.

pip install larz
@app.websocket("/ws/")
async def chat(ws):
    await ws.accept()
    async for msg in ws:                 # iterate incoming messages
        await ws.send("echo: " + msg)    # or ws.send_json({...})

app.run_async()                          # built-in asyncio server (RFC 6455)

QuickstartGitHubDocs

The WebSocket object

accept(), receive() (text or bytes), send() / send_json(), close(), path params on ws.params, and async for msg in ws to loop until the client disconnects. It works on the built-in server or any ASGI server (uvicorn/hypercorn/daphne).

FAQ

Do WebSockets need uvicorn?

They work on any ASGI server, and also on Larz's built-in zero-dependency asyncio server (app.run_async), which implements RFC 6455.

How do I broadcast to a room?

Keep a set of connected WebSocket objects per room (the path param) and loop send() over them — see the async_chat example.