Python / Uvicorn Fundamentals Interview Questions
How does Uvicorn handle WebSocket connections?
Uvicorn has native WebSocket support, making it suitable for real-time applications like chat, live dashboards, and collaborative tools. WebSocket connections are handled via the websockets or wsproto library.
# Pure ASGI WebSocket application async def app(scope, receive, send): if scope["type"] == "websocket": # Accept the WebSocket connection await send({"type": "websocket.accept"}) while True: event = await receive() if event["type"] == "websocket.receive": data = event.get("text") or event.get("bytes") # Echo the message back await send({"type": "websocket.send", "text": data}) elif event["type"] == "websocket.disconnect": break # FastAPI WebSocket example from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Echo: {data}")
| Flag | Default | Description |
|---|---|---|
| --ws | auto | WebSocket implementation: auto, websockets, websockets-sansio, wsproto |
| --ws-max-size | 16777216 (16MB) | Maximum WebSocket message size in bytes |
| --ws-max-queue | 32 | Maximum WebSocket message queue length |
| --ws-ping-interval | 20.0s | Interval between server ping frames |
| --ws-ping-timeout | 20.0s | Timeout waiting for pong response |
| --ws-per-message-deflate | True | Enable per-message compression |
Note: the WSGI interface (--interface wsgi) always disables WebSocket support because WSGI does not define a WebSocket protocol. Use the ASGI interface for WebSocket-capable applications.
More Related questions...