new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

websockets

7 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

WebSocket API syntax in FastAPI

To create a WebSocket endpoint in FastAPI, use the @app.websocket decorator with a path. FastAPI provides the WebSocket class directly from Starlette for convenience. WebSocket is imported from fastapi.websockets.

Await for messages and send messages in WebSocket

In a WebSocket route handler, you can await for messages and send messages. The websocket object supports receiving and sending binary, text, and JSON data. Use await websocket.receive_text() to receive text messages and await websocket.send_text() to send text messages.

WebSocket dependency injection

In WebSocket endpoints you can import from fastapi and use Depends, Security, Cookie, Header, Path, and Query. They work the same way as for other FastAPI endpoints and path operations.

WebSocketException vs HTTPException in WebSocket endpoints

In WebSocket endpoints, raise WebSocketException instead of HTTPException. Use a closing code from the valid codes defined in RFC 6455 section 7.4.1.

WebSocketDisconnect exception handling

When a WebSocket connection is closed, await websocket.receive_text() will raise a WebSocketDisconnect exception. You can catch and handle this exception to detect when clients disconnect from the WebSocket.

WebSocket installation requirement

To use WebSockets with FastAPI, add the websockets library to your project. This is a Python library that makes it easy to use the WebSocket protocol.

In-memory WebSocket broadcasting limitations

When handling multiple WebSocket clients and broadcasting messages using in-memory lists, the solution only works while the process is running and only works with a single process. For production use with multiple processes, consider using libraries like encode/broadcaster that integrate with FastAPI and support Redis or PostgreSQL.

Give your agent this brain