FastAPI 怎样建立 WebSocket 并处理消息?
查看完整题解
参考回答
直接回答
用 @app.websocket 定义入口。建立连接后,可以在同一个连接上多次接收与发送数据。应明确验证身份、可访问频道、消息格式和大小。
讲清原理
与普通一次性 HTTP 请求不同,连接可能长时间保持。服务端要处理断开和资源清理。多副本部署时还要考虑连接归属和状态共享。
例子与易错点
示例通过测试客户端连接,发送两条独立消息并读取回应;该测试覆盖接口行为,线上代理与 TLS 仍需独立联调。
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.testclient import TestClient
app = FastAPI()
@app.websocket("/ws/echo")
async def echo(socket: WebSocket):
await socket.accept()
try:
while True:
message = await socket.receive_text()
await socket.send_text(f"received {message}")
except WebSocketDisconnect:
return
with TestClient(app) as client, client.websocket_connect("/ws/echo") as socket:
for word in ("one", "two"):
socket.send_text(word)
assert socket.receive_text() == f"received {word}"
print("two messages on one connection")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。