تنفيذ WebSockets في FastAPI
تعلّموا إضافة نقاط نهاية WebSocket إلى تطبيق FastAPI وإدارة الاتصالات.
تنفيذ WebSockets في FastAPI درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في FastAPI Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Real-time with FastAPI WebSockets
Welcome to implementing WebSockets with FastAPI! WebSockets provide a persistent, full-duplex communication channel between a client and a server.
- Full-duplex: Both client and server can send and receive messages simultaneously.
- Real-time: Ideal for applications needing instant updates, like chat, live dashboards, or gaming.
FastAPI has excellent built-in support for WebSockets, leveraging Python's async/await features.
Defining a WebSocket Endpoint
Just like HTTP endpoints, you define WebSocket endpoints using a decorator. Instead of @app.get() or @app.post(), you use @app.websocket().
Your endpoint function must be async def and accept a websocket: WebSocket parameter. This WebSocket object is your primary tool for interaction.
The first step inside your function is always to await websocket.accept() to establish the connection.
Your First WebSocket Connection
Let's create our first WebSocket endpoint. This simple example accepts a connection, sends a welcome message, and then closes the connection.
Notice the @app.websocket("/ws") decorator and the async def function, which are key for WebSocket handling.
Try running this example and observe the connection:
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text("Welcome! Connection established.")
await websocket.close()Handling WebSocket Disconnections
WebSocket connections can be interrupted for various reasons (client closes tab, network error). It's crucial to handle these disconnections gracefully.
FastAPI raises a WebSocketDisconnect exception when a client disconnects. You can catch this exception to perform cleanup tasks, like removing the client from a list of active connections.
Wrap your WebSocket communication logic in a try...except WebSocketDisconnect block.
Receiving Messages from Clients
Once connected, your server can receive messages from the client. The WebSocket object provides methods for this:
await websocket.receive_text(): For receiving string data.await websocket.receive_bytes(): For receiving binary data.await websocket.receive_json(): For receiving JSON data (requirespython-multipart).
These operations are asynchronous, so always use await.
Echoing Client Messages Back
This example demonstrates a simple 'echo' server. It accepts a connection, then continuously receives messages from the client and sends them back.
The while True loop keeps the connection open, and the try...except WebSocketDisconnect handles when the client leaves.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket("/ws/echo")
async def websocket_echo(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
print(f"Received from client: {data}")
await websocket.send_text(f"Server echoed: {data}")
except WebSocketDisconnect:
print("Client disconnected.")Sending Messages to Clients
Similarly, your server can send messages to the client. The WebSocket object offers:
await websocket.send_text("your message"): To send string data.await websocket.send_bytes(b"your bytes"): To send binary data.await websocket.send_json({"key": "value"}): To send JSON data.
Remember to await these calls. It's common to send a response right after receiving a message.
Working with JSON Data
For structured data, sending and receiving JSON is preferred. FastAPI's WebSocket object handles serialization/deserialization for you.
- Sending: Pass a Python
dicttosend_json(). - Receiving:
receive_json()returns a Pythondict.
This simplifies data exchange compared to manually parsing strings.
Simple Connection Manager
For applications with multiple clients, you'll need to manage active connections. A common pattern is to use a class to keep track of all connected WebSocket objects.
This manager can then be used to add/remove connections and send messages to specific clients or broadcast to all.
from fastapi import WebSocket
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_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
# In a real app, you'd integrate 'manager' into your FastAPI endpoint
manager = ConnectionManager()WebSocket Interaction Check
You've learned the basics of setting up and interacting with WebSocket connections in FastAPI.
Let's check your understanding of accepting new connections.
Recap: Implementing WebSockets
You've successfully learned how to implement WebSockets in FastAPI!
- Use
@app.websocket()to define endpoints. - Always
await websocket.accept()to establish the connection. - Handle disconnections with
try...except WebSocketDisconnect. - Use
await websocket.receive_text()andawait websocket.send_text()for communication. - For structured data,
send_json()andreceive_json()are your friends.
Next, you'll build a real-time chat application to put these concepts into practice!
الأسئلة الشائعة
هل درس «تنفيذ WebSockets في FastAPI» مجاني؟
نعم — نص درس «تنفيذ WebSockets في FastAPI» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.
ماذا ستتعلم في «تنفيذ WebSockets في FastAPI»؟
تعلّموا إضافة نقاط نهاية WebSocket إلى تطبيق FastAPI وإدارة الاتصالات. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.
كم من الوقت يستغرق درس «تنفيذ WebSockets في FastAPI»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟
نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- أساسيات بروتوكول WebSocket
- تنفيذ WebSockets في FastAPI
- بناء تطبيق دردشة في الوقت الفعلي
- توسيع WebSockets باستخدام وسيط Pub/Sub