Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8.7k
Comments
✨ ExportWebSocketState infastapi.websockets#4376
Conversation
9fa01ba to87b8536CompareKludex commentedAug 31, 2022
How do you use |
matiuszka commentedAug 31, 2022
So there is an endpoint that is sending some data, usually very rarely but still, and is receiving nothing. So while we are not sending any data and the WebSocket connection was closed by the client, the task is still running. So to add functionality that if the connection is closed task will be closed also we are monitoring the WebSocket status, by simple The endpoint more or less looks like that: @router.websocket("/subscribe/some/data/changes")asyncdefsubscribe_connectors_status(websocket:WebSocket,)->None:asyncdefsend_some_data()->None:last_data=awaitget_data()awaitwebsocket.send_json({"data":last_data})whileTrue:awaitasyncio.sleep(1)new_data=awaitget_data()ifnew_data!=last_data:# This happens very rarely that's why I would like to close all of these unused tasks.last_data=new_dataawaitwebsocket.send_json({"foo":last_data})asyncdefwatch_status()->None:whilewebsocket.client_state==WebSocketState.CONNECTED:# We are not expecting any data, but this will change to the client state if the connection will be closed.awaitwebsocket.receive()tg.cancel_scope.cancel()awaitwebsocket.accept()asyncwithcreate_task_group()astg:tg.start_soon(watch_status)tg.start_soon(send_some_data) |
codecovbot commentedAug 31, 2022 • edited
Loading Uh oh!
There was an error while loading.Please reload this page.
edited
Uh oh!
There was an error while loading.Please reload this page.
Codecov Report
@@ Coverage Diff @@## master #4376 +/- ##========================================= Coverage 100.00% 100.00% ========================================= Files 535 535 Lines 13825 13826 +1 =========================================+ Hits 13825 13826 +1
Help us with your feedback. Take ten seconds to tell ushow you rate us. Have a feature suggestion?Share it here. |
📝 Docs preview for commit36dadce at:https://630fd8992dbce202ce9f181a--fastapi.netlify.app |
WebSocketStateWebSocketState infastapi.websocketstiangolo commentedSep 4, 2022
Thanks for the contribution@matiuszka! 🍰 And thanks@Kludex for the help! 🙇 Knowing how you are using it made me feel it makes sense to have this in, so I'll take it. 🚀 Thanks! ☕ |
Trivial improvement about exposing
WebSocketState. It will eliminate the need of importing it fromstarlettedirectly.Previously:
After: