Home > Web Front-end > JS Tutorial > How can I dynamically update an HTML template with real-time data streamed from a Flask view?

How can I dynamically update an HTML template with real-time data streamed from a Flask view?

Barbara Streisand
Release: 2024-11-29 07:50:09
Original
321 people have browsed it

How can I dynamically update an HTML template with real-time data streamed from a Flask view?

Stream Data into a Dynamically Updated HTML Template

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:

Using XMLHttpRequest:

  1. Perform an XMLHttpRequest request to fetch streamed data from the endpoint.
  2. Implement a polling mechanism (e.g., setInterval) to check for new data.
  3. When new data is received, parse and display it in the HTML (e.g., using DOM manipulation).
  4. Continuously handle data until the stream ends (or display a completion message).
# 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);
Copy after login

Using an