Updating webpage from background thread using sock

2019-05-28 22:53发布

In almost every single example I've found of Flask/Socket.io, Socket.io triggers an event which is then processed by the Flask app, and dealt whatever response.

I need to consistently push new data to the page, without having an event trigger. In the Flask/Socket.io online tutorial, they briefly mention this, but I'm sort of stuck.

As of now, I'm only pushing up data on client connects, making a new thread for every connection. Here is my code for that:

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread objects
    print "We're working"
    global thread
    print('Client connected')

if not thread.isAlive():
    print "Starting Thread"
    thread = RandomThread()
    thread.start()

And then:

class RandomThread(Thread):
    def __init__(self):
        self.delay = 6
        super(RandomThread, self).__init__()

        ## Find Tweets every X amount of seconds
        def tweetFinder(self):
        print "Finding Tweets..."

        while not thread_stop_event.isSet():
            twit = Twitter()
            twit.login()
            cityName = twit.getUserTweets()
            print cityName
            socketio.emit('newnumber', {'number': cityName}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.tweetFinder()

But how do I get this thread/process of pushing up data started right when the application is launched? I just want it working as an ongoing, infinite task in the backend, updating the page regardless of events.

Here is what the Flask/Socket-io docs say, I just can't figure out how to make it work the way I want it to.

In all the examples shown until this point the server responds to an event sent by the client. But for some applications, the server needs to be the originator of a message. This can be useful to send notifications to clients of events that originated in the server, for example in a background thread. The socketio.send() and socketio.emit() methods can be used to broadcast to all connected clients:

def some_function():
    socketio.emit('some event', {'data': 42})

Note that in this usage there is no client context, so broadcast=True is assumed and does not need to be specified.

0条回答
登录 后发表回答