Flask, Python and Socket.io: multithreading app is giving me "RuntimeError: working outside of request context" Flask, Python and Socket.io: multithreading app is giving me "RuntimeError: working outside of request context" flask flask

Flask, Python and Socket.io: multithreading app is giving me "RuntimeError: working outside of request context"


Your error is 'working outside of request context'. You tried to resolve it by pushing the application context. Instead you should push the request context. See the explanation on contexts in flask on http://kronosapiens.github.io/blog/2014/08/14/understanding-contexts-in-flask.html

The code in your somefunction() probably uses objects (if i had to guess you probably use the request object) that are global inside the request context. Your code probably works when it is not executed inside the new thread. But when you execute it in a new thread your function is not executed in the original request context anymore and it does not have access to the request context specific objects anymore. So you have to push it manually.

so your function should be

def someotherfunction():    with app.test_request_context('/'):        emit('anEvent', jsondata, namespace='/test')


You are using the wrong emit here. You have to use the emit of the socketio object you created. so instead of

emit('anEvent', jsondata, namespace='/test') # here occurs the erroruse:socketio.emit('anEvent', jsondata, namespace='/test') # here occurs the error