I need help with the python web frame work, Quart, more specifically the websockets. I would like to be able to register a client when it connects (add it to a python list), and unregister them (remove it from the python list) when it disconnects. The closest thing I could find on the web is this code:
connected = set()
async def handler(websocket, path):
global connected
# Register.
connected.add(websocket)
try:
# Implement logic here.
await asyncio.wait([ws.send("Hello!") for ws in connected])
await asyncio.sleep(10)
finally:
# Unregister.
connected.remove(websocket)
But this does not work with quart websockets.
Help would be appreciated.
This decorator when used to wrap a websocket handler, will add and remove websockets from the
connected
set. The_get_current_object
method of the websocket is required to get the websocket in the current context, and the try-finally is required to ensure the websocket is removed regardless of any errors that are raised. Note theapp.websocket
must wrap (be before) thecollect_websocket
usage.Edit: I am the Quart author.