Well, it depends on the architecture of your application.
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")
The flask will request a new Redis message (blocking operation) steadily, but when Flask sees that the streaming completes ( StopIteration
, if you are not 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")
source share