I am trying to create a \'keepalive\' websocket thread to send an emit every 10 seconds to the browser once someone connects to the page, but I\'m getting an error and am no
You wrote your background thread in a way that requires it to know who's the client, since you are sending a direct message to it. For that reason the background thread needs to have access to the request context. In Flask you can install a copy of the current request context in a thread using the copy_current_request_context
decorator:
@copy_current_request_context
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'websocket is keeping alive'}, namespace='/endpoint')
Couple of notes:
emit
call will be on the same namespace used by the client. The namespace needs to be specified when you broadcast or send messages outside of a request context.To stop the thread when the client disconnects you can use any multi-threading mechanism to let the thread know it needs to exit. This can be, for example, a global variable that you set on the disconnect event. A not so great alternative that is easy to implement is to wait for the emit
to raise an exception when the client went away and use that to exit the thread.