How to close Server-Send Events connection in Flask?

Below is the answer using node.js.

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

However, how to do the same in python Flask?

+6
source share
1 answer

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") 
+3
source

Source: https://habr.com/ru/post/921052/


All Articles