I'm trying to implement server push in my Flask project following this tutorial.
I've set it all up with no errors, however when I go to the /stream page, Firefox recognizes it as a file and tries to download it. In Safari it just prints out the data sent. I tried adapting the code to a simpler implementation, where a thread just yields some data each second, however it produced the same results.
My goal is for each time a python script reaches a point in a loop, it will update a progress bar on the web interface.
Any help with this would be great. Thanks.
Edit:
app.py
from flask import Flask, render_template, request, Response
app = Flask(__name__)
def event_stream():
event = "Hello!"
yield 'data: %s
' % event
@app.route('/stream')
def stream():
return Response(event_stream(), mimetype="text/event-stream")
if __name__ == "__main__":
app.debug = True
app.run(threaded=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var source = new EventSource('/stream');
source.onmessage = function (event) {
alert(event.data);
};
</script>
</head>
<body>
<p>Stream page</p>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…