Cum să implementezi WebSocket într-un API Python cu FastAPI
In this tutorial, you'll learn about Cum să implementezi WebSocket într. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
WebSocket permite comunicare bidirecțională în timp real între client și server. În acest ghid vei învăța cum să implementezi WebSocket într-un API Python cu FastAPI și Flask-SocketIO.
Problema
API-ul tău HTTP tradițional nu poate trimite date către client în timp real. Pentru notificări live, chat sau actualizări de status, ai nevoie de o conexiune persistentă bidirectională.
Soluția Rapidă
1. WebSocket cu FastAPI
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import List
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 send_personal(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.send_personal(
f"Primit: {data}", websocket
)
await manager.broadcast(
f"Client {client_id} a trimis: {data}"
)
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(
f"Client {client_id} s-a deconectat"
)
2. Client WebSocket în JavaScript
const ws = new WebSocket("ws://localhost:8000/ws/user1");
ws.onopen = () => {
console.log("Conexiune WebSocket stabilită");
ws.send("Salut server!");
};
ws.onmessage = (event) => {
console.log("Mesaj primit:", event.data);
};
ws.onclose = () => {
console.log("Conexiunea s-a închis");
};
3. WebSocket cu Flask-SocketIO
pip install flask-socketio
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
@socketio.on("conectare")
def handle_conectare():
emit("mesaj", {"data": "Bine ai venit!"})
@socketio.on("mesaj_client")
def handle_mesaj(data):
print(f"Primit: {data}")
emit("raspuns", {"data": f"Ai spus: {data['text']}"})
if __name__ == "__main__":
socketio.run(app, debug=True)
4. Gestionarea camerelor de chat
from fastapi import WebSocket
rooms = {}
@app.websocket("/ws/chat/{room_id}")
async def chat_room(websocket: WebSocket, room_id: str):
await websocket.accept()
if room_id not in rooms:
rooms[room_id] = []
rooms[room_id].append(websocket)
try:
while True:
data = await websocket.receive_text()
for client in rooms[room_id]:
if client != websocket:
await client.send_text(data)
except WebSocketDisconnect:
rooms[room_id].remove(<a href="/apis/websocket/">WebSocket</a>)
5. Keepalive și reconectare
function conectareWebSocket() {
const ws = new WebSocket("ws://localhost:8000/ws");
ws.onclose = () => {
setTimeout(conectareWebSocket, 3000);
};
// Ping la fiecare 30 de secunde
setInterval(() => {
if (ws.readyState === <a href="/apis/websocket/">Websocket</a>.OPEN) {
ws.send(JSON.stringify({ tip: "ping" }));
}
}, 30000);
}
Prevenție
- Implementează reconectare automată pe client
- Trimite ping/pong pentru menținerea conexiunii
- Limitează numărul de conexiuni simultane per client
- Folosește autentificare în query string-ul WebSocket
- Închide conexiunile inactive pentru a elibera resurse
Greșeli Comune
- Fără gestionarea deconectării -- conexiunile abandonate rămân în memorie
- Transmiterea datelor neautentificate -- WebSocket-ul trebuie să verifice token-ul la conectare
- Fără limitare a ratei -- un client poate trimite mii de mesaje pe secundă
- Reconectare fără backoff exponențial -- toți clienții se reconectează simultan după o cădere de server
- Ignorarea erorilor de conexiune -- conexiunile instabile trebuie tratate gracefully
Exercițiu Practic
Implementează un WebSocket server care gestionează camere de chat multiple. Fiecare cameră permite utilizatorilor să trimită mesaje care sunt broadcastate celorlalți membri.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro