EventSource, stream.onmessage, Response()
javascript side
var stream = new EventSource('/api/stream'); stream.onmessage = function(e) { console.info(e.data); $("#received").append(e.data+"\n"); $("#received")[0].scrollTop = $("#received")[0].scrollHeight; };python side
#from queue import Queue #from flask import Response queue = Queue() def event_stream(): while True: # Question: how to break out of this loop when the app is killed? message = queue.get(True) print("Sending {}".format(message)) yield "data: {}\n\n".format(message) @app.route('/api/stream') def stream(): return Response(event_stream(), mimetype="text/event-stream")
reference
https://www.w3schools.com/html/html5_serversentevents.asp