1

我正在尝试使用 starlette 构建一个 Web 套接字,它接收消息,在同步函数中运行计算并返回响应。

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        stock = await websocket.receive_text()
        stock = stock.upper()
        data = sentiment_analysis(stock=stock)
        await websocket.send_json({"score": data})

情绪分析是一个同步功能。

因此接收到文本并运行计算,如果我打印数据变量(字典),我看到它已正确返回,但是当我尝试将其发送回客户端时,出现以下错误:

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/uvicorn/protocols/websockets/websockets_impl.py", line 153, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/fastapi/applications.py", line 179, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/applications.py", line 111, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/middleware/errors.py", line 146, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 283, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/dist-packages/starlette/routing.py", line 57, in app
    await func(session)
  File "/usr/local/lib/python3.8/dist-packages/fastapi/routing.py", line 228, in app
    await dependant.call(**values)
  File "./app.py", line 13, in websocket_endpoint
    stock = await websocket.receive_text()
  File "/usr/local/lib/python3.8/dist-packages/starlette/websockets.py", line 85, in receive_text
    self._raise_on_disconnect(message)
  File "/usr/local/lib/python3.8/dist-packages/starlette/websockets.py", line 80, in _raise_on_disconnect
    raise WebSocketDisconnect(message["code"])
starlette.websockets.WebSocketDisconnect: 1011  
4

1 回答 1

0

WebSocketDisconnect当客户端关闭连接时,您需要处理异常。它可以是这样的:

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            stock = await websocket.receive_text()
            stock = stock.upper()
            data = sentiment_analysis(stock=stock)
            await websocket.send_json({"score": data})
    except WebSocketDisconnect:
        handle_exception()
        ...
    else:
        await websocket.close()
于 2021-01-02T20:58:58.700 回答