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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
