Problem:
Generating and streaming data in real-time from a Flask view, we want to display it dynamically within a formatted HTML template.
Answer:
Streaming data within a Flask response is possible, however, it's not feasible to update client-side content directly. To achieve desired, utilize JavaScript and the following methods:
# Server-side Flask code @app.route("/stream") def stream(): def generate(): for i in range(500): yield "{}\n".format(sqrt(i)) sleep(1) return app.response_class(generate(), mimetype="text/plain") # Client-side JavaScript var timer = setInterval(function() { // Handle new data if (xhr.readyState == XMLHttpRequest.DONE) { clearInterval(timer); } }, 1000);
# Server-side Flask code @app.route("/stream") def stream(): @stream_with_context def generate(): yield render_template_string('<link rel=stylesheet href="{{ url_for("static", filename="stream.css") }}">') for i in range(500): yield render_template_string("<p>{{ i }}: {{ s }}</p>\n", i=i, s=sqrt(i)) sleep(1) return app.response_class(generate())
<!-- Client-side HTML --> <iframe src="{{ url_for("stream") }}"></iframe>
Note:
The above is the detailed content of How can I dynamically update an HTML template with real-time data streamed from a Flask view?. For more information, please follow other related articles on the PHP Chinese website!