Streaming Data Updates with Flask
Integrating live data streams into HTML templates can pose challenges due to the static nature of templates rendered on the server. However, there are approaches to achieve this functionality.
To stream data without modifying the template dynamically, JavaScript can be employed. By issuing a request to a streaming endpoint, the client-side JavaScript can read and display the data in real time. This approach introduces complexity but offers greater control over the output appearance.
For example, the following code demonstrates how to display both the latest value and a log of all received values:
setInterval(() => { var latest = document.getElementById('latest'); var output = document.getElementById('output'); var xhr = new XMLHttpRequest(); xhr.open('GET', '{{ url_for('stream') }}'); xhr.send(); var position = 0; function handleNewData() { var messages = xhr.responseText.split('\n'); messages.slice(position, -1).forEach(function(value) { latest.textContent = value; var item = document.createElement('li'); item.textContent = value; output.appendChild(item); }); position = messages.length - 1; } timer = setInterval(function() { handleNewData(); if (xhr.readyState === XMLHttpRequest.DONE) { clearInterval(timer); latest.textContent = 'Done'; } }, 1000); }, 1000);
Alternatively, an
<p>This is all the output:</p> <iframe src="{{ url_for('stream') }}"></iframe>
iframe { width: 300px; height: 200px; }
@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())
Ultimately, the choice between streaming data via JavaScript or
The above is the detailed content of How Can I Efficiently Stream Live Data Updates into Flask HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!