2

我有一个用快速 api 构建的小型 WebSocket。我正在尝试从客户端接收消息,对其进行处理并返回 JSON 响应。

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        story = await websocket.receive_text()
        data = sentiment_analysis(news=story)
# Exmaple out put of sentiment_analysis function: {'compound_score': 0.5856095238095237, 'correlation_score': 0.8736042200587304}

        await websocket.send_json(json.dumps(data))

来自客户端的消息按应有的方式接收和处理,但我似乎无法将响应字典加载到 JSON 并将其发回。

我收到一个错误:

  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 20, 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

1

如果您正在使用,websocket.send_json()那么您不需要这样做json.dumps(),因为这只是将其解析为字符串文本。

另外我发现这@app.websocket()对我不起作用,我需要使用websocket_route()装饰器。FastAPI 一直抛出 WebSocketDisconnect,直到我使用了websocket_route()装饰器。

注意:我使用的是装饰器,APIRouter()而不是FastAPI()一粒盐,但我相信最新版本的 FastAPI 支持websocket_route()两者。

下面的代码应该适用于这两个修改


@app.websocket_route("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        story = await websocket.receive_text()
        data = sentiment_analysis(news=story)
        await websocket.send_json(data)
于 2020-12-30T21:45:18.643 回答