RuntimeError: working outside of request context

前端 未结 1 482
孤独总比滥情好
孤独总比滥情好 2021-01-18 05:36

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

相关标签:
1条回答
  • 2021-01-18 06:05

    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:

    • It is not necessary to set the namespace when you are sending back to the client, by default the 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.
    • Keep in mind your design will require a separate thread for each client that connects. It would be more efficient to have a single background thread that broadcasts to all clients. See the example application that I have on the Github repository for an example: https://github.com/miguelgrinberg/Flask-SocketIO/tree/master/example

    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.

    0 讨论(0)
提交回复
热议问题