How do I close a Server-Send Events connection in Flask?


Question

The below has given an answer using node.js.

How to close a "Server-Sent Events"-connection on the server?

However, how to do the same thing in python Flask?

1
8
5/23/2017 12:09:29 PM

Well, it depends on the architecture of your app.

Let me show you an example (see this code at https://github.com/jkbr/chat/blob/master/app.py):

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        print message
        yield 'data: %s\n\n' % message['data']

@app.route('/stream')
def stream():
    return flask.Response(event_stream(),
                          mimetype="text/event-stream")

Flask asks a new message to Redis (locking operation) steadily, but when Flask sees that streaming terminates (StopIteration, if you aren't new to Python), it returns.

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        if i_should_close_the_connection:
            break
        yield 'data: %s\n\n' % message['data']

@app.route('/stream')
def stream():
    return flask.Response(event_stream(),
                          mimetype="text/event-stream")
3
10/31/2012 7:06:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon