-
-
Notifications
You must be signed in to change notification settings - Fork 855
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to reject a websocket request #494
Comments
Did you try to accept it first, then close? class DemoWs(WebsocketEndpoint):
async def on_connect(self, websocket):
await websocket.accept()
if should_disconnect(websocket):
await websocket.close() |
You’ve forgotten to return after the close, so I guess you’re falling through to the accept block. (Though the exception isn’t very clear) |
@unmade @tomchristie thanks to your reply. I found the exception was throw in https://github.com/encode/starlette/blob/master/starlette/endpoints.py#L65 class DemoWs(WebsocketEndpoint):
async def on_connect(self, websocket):
if should_disconnect(websocket):
await websocket.close()
return
await websocket.accept()
async def __call__(self, receive: Receive, send: Send) -> None:
websocket = WebSocket(self.scope, receive=receive, send=send)
await self.on_connect(websocket)
close_code = status.WS_1000_NORMAL_CLOSURE
try:
while True:
#workaround, catach the Exception if websocket handshake not finished
try:
message = await websocket.receive()
except TypeError:
break
if message["type"] == "websocket.receive":
data = await self.decode(websocket, message)
await self.on_receive(websocket, data)
elif message["type"] == "websocket.disconnect":
close_code = int(message.get("code", status.WS_1000_NORMAL_CLOSURE))
break
except Exception as exc:
close_code = status.WS_1011_INTERNAL_ERROR
raise exc from None
finally:
await self.on_disconnect(websocket, close_code) |
The problem with the snippet posted is that it's missing a return statement. class DemoWs(WebsocketEndpoint):
async def on_connect(self, websocket):
if should_disconnect(websocket):
await websocket.close()
# return
await websocket.accept() |
Hi @tomchristie Thank you for the response, but adding "return" won't solve the problem. The exception is thrown here: https://github.com/encode/starlette/blob/master/starlette/endpoints.py#L65 when websocket tries to receive after it is closed. Adding "return" will return to line https://github.com/encode/starlette/blob/master/starlette/endpoints.py#L59 , but it will still try to do the following |
Gotcha, so we should be checking if the websocket was closed at starlette/starlette/endpoints.py Line 59 in c294ba6
|
Seems so. But I am not sure in this case, should it still call the |
i write the code below
but the exception happened
The text was updated successfully, but these errors were encountered: