RuntimeError: working out of request context

I am trying to create a "keepalive" websocket stream to send the emitter every 10 seconds to the browser as soon as someone connects to this page, but receives an error message and does not know how to get around it. Any idea how to make this work. And how can I kill this thread after sending the "disconnect"?

Thanks!

@socketio.on('connect', namespace='/endpoint') def test_connect(): emit('my response', {'data': '<br>Client thinks i\'m connected'}) 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') global thread if thread is None: thread = Thread(target=background_thread) thread.start() 
+7
python flask websocket flask-socketio
source share
1 answer

You wrote your background thread so that it knows who the client is, since you send him a direct message. For this reason, the background thread must have access to the request context. In Flask, you can set a copy of the current request context in the stream 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') 

A couple of notes:

  • There is no need to set the namespace when sending back to the client; by default, the emit call will be in the same namespace that the client uses. The namespace must be specified when sending or sending messages outside the context of the request.
  • Keep in mind that for your project you will need a separate thread for each connected client. It would be more efficient to have one background thread that is passed to all clients. See the sample application that I have in the Github repository, for example: https://github.com/miguelgrinberg/Flask-SocketIO/tree/master/example

To stop the thread when the client disconnects, you can use any multithreading mechanism so that the thread knows that it needs to exit. It could be, for example, a global variable that you set in the disconnect event. A not so great alternative that is easy to implement is to wait for emit exception, when the client leaves and uses it to exit the stream.

+8
source share

All Articles