Terminate long polling event after user disconnects #1720
-
I have an event that that polls a certain Redis queue and emits the results back to the client. I would like this emission to stop once the user hangs up to prevent resources from getting used up and running infinite loops. My current understanding is this so far :-
class SocketNameSpace(Namespace):
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_subscribe(self, payload):
# Retrieve relevant details from DB using MySQL Alchemy
# Subscribe to appropriate redis pubsub object
redisClient = r.pubsub()
while True:
socketio.sleep(0)
message = redisClient.get_message(timeout)
if message:
socketio.emit("subscribe_response_event", message)
#Emit to client
# The part I would like to implement somehow
if current_user.disconnect():
break
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Yes, this is not the best way to do what you need. Unfortunately the correct way is much harder. What you want to do in your subscribe event handler is to start a background task to monitor redis, and then return immediately. def on_subscribe(self, payload):
socketio.start_background_task(watch_redis, request.sid) Then you can have an independent redis watcher task: def watch_redis(sid):
redisClient = r.pubsub()
while True:
socketio.sleep(0)
message = redisClient.get_message(timeout)
if message:
socketio.emit("subscribe_response_event", message, to=sid)
#Emit to client Then there is the part about stopping this background task when the client disconnects. For that you can add an |
Beta Was this translation helpful? Give feedback.
Yes, this is not the best way to do what you need. Unfortunately the correct way is much harder.
What you want to do in your subscribe event handler is to start a background task to monitor redis, and then return immediately.
Then you can have an independent redis watcher task:
Then there is the part about stopping this backgroun…