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

后端 未结 2 1197
半阙折子戏
半阙折子戏 2021-02-19 09:33

I have been developing an app using Flask, Python and Flask-Socket.io library. The problem I have is that the following code w

相关标签:
2条回答
  • 2021-02-19 09:43

    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 error use: socketio.emit('anEvent', jsondata, namespace='/test') # here occurs the error

    0 讨论(0)
  • 2021-02-19 09:58

    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')
    
    0 讨论(0)
提交回复
热议问题