我需要断开传入的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'
我需要让客户端知道由于特定原因连接被拒绝。请让我知道我在这里做错了什么。
谢谢你的时间。
2条答案
按热度按时间lzfw57am1#
我正在运行旧版本的FastAPI,它的
close()
不支持“reason”参数。将FastAPI升级到最新版本解决了这个问题,因为最近引入了“原因”参数。bvk5enib2#
潜在的旁观者有类似的问题。
如果您希望发送的原因数据更有表现力,则可能会被控制帧的规范约束所捕获。
关闭(控制帧)时发送的最大字节数,由125个字节组成