fastapi requests.receive
时间: 2023-10-05 10:10:15 浏览: 40
`requests.receive()` is a method in FastAPI's WebSocket class. It is used to receive incoming messages from the client in real time.
When a WebSocket connection is established between the client and the server, the client can send messages to the server at any time. To receive these messages, the server can call the `requests.receive()` method. This method blocks until a message is received from the client.
Here is an example of using `requests.receive()` in a FastAPI WebSocket endpoint:
```python
from fastapi import FastAPI, WebSocket
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections = []
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:
message = await websocket.receive_text()
await manager.broadcast(message)
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{websocket} left the chat")
```
In this example, the `requests.receive()` method is used in a loop to continuously receive messages from the client. The `WebSocketDisconnect` exception is caught to gracefully handle disconnection from the client.