FastAPI/Starlette websocket.close() 不接受"reason"参数



我需要断开一个传入的WebSocket连接,以防用户已经与服务器有一个实时连接,为此我在Starlette文档中建议调用websocket.close()。但是,当我调用以下代码时:

await websocket.close(code=1000, reason='Connection refused as session already exists for user')

服务器崩溃,并显示以下堆栈跟踪信息:unexpected keyword argument 'reason':

app_1     | Traceback (most recent call last):
app_1     |   File "/usr/local/lib/python3.10/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 184, in run_asgi
app_1     |     result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
app_1     |     return await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/fastapi/applications.py", line 211, in __call__
app_1     |     await super().__call__(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/applications.py", line 112, in __call__
app_1     |     await self.middleware_stack(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/errors.py", line 146, in __call__
app_1     |     await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/base.py", line 22, in __call__
app_1     |     await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/middleware/cors.py", line 76, in __call__
app_1     |     await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/exceptions.py", line 58, in __call__
app_1     |     await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 656, in __call__
app_1     |     await route.handle(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 315, in handle
app_1     |     await self.app(scope, receive, send)
app_1     |   File "/usr/local/lib/python3.10/site-packages/starlette/routing.py", line 77, in app
app_1     |     await func(session)
app_1     |   File "/usr/local/lib/python3.10/site-packages/fastapi/routing.py", line 273, in app
app_1     |     await dependant.call(**values)
app_1     |   File "/app/code/./app/api/api_v1/ws/ws_manager.py", line 175, in websocket_endpoint
app_1     |     await manager.connect(user, websocket)
app_1     |   File "/app/code/./app/api/api_v1/ws/ws_manager.py", line 90, in connect
app_1     |     await websocket.close(code=1000, reason='Connection refused as session already exists for user')
app_1     | TypeError: WebSocket.close() got an unexpected keyword argument 'reason'

我需要让客户端知道由于特定原因连接被拒绝。请告诉我哪里做错了。

感谢您的宝贵时间。

我正在运行一个旧版本的FastAPI,其close()不支持"reason"论点。升级FastAPI到最新版本解决了"原因"问题;

可能对旁观者有类似的问题。

如果你想表达你想发送的原因数据,你可能会被控制帧的规范约束所抓住。

在关闭(控制帧)上发送的最大字节数,由125字节组成

最新更新