Performance: WebSocket endpoint creation
MEDIUM IMPACT
This affects the responsiveness and resource usage of real-time communication on the page, impacting interaction speed and server load.
from fastapi import FastAPI, WebSocket from fastapi.websockets import WebSocketDisconnect app = FastAPI() class ConnectionManager: def __init__(self): self.active_connections: list[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) manager = ConnectionManager() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_text() await manager.broadcast(f"Client says: {data}") except WebSocketDisconnect: manager.disconnect(websocket)
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"Message text was: {data}")
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Basic WebSocket endpoint without connection management | 0 (server-side) | 0 | 0 | [X] Bad |
| WebSocket endpoint with connection manager and broadcast | 0 (server-side) | 0 | 0 | [OK] Good |