How to Display Real-time Data Streamed from a Flask View?
Displaying Data Streamed from a Flask View in Real Time
Introduction
When working with real-time data, it's often desirable to display the data as it becomes available. With Flask, this can be challenging as templates are rendered only once on the server side. This article explores how to overcome this limitation, allowing for the dynamic display of streamed data in a larger templated page.
Utilizing JavaScript and XMLHttpRequest
The most versatile approach involves using JavaScript and XMLHttpRequest to periodically retrieve data from a streamed endpoint. The received data can then be dynamically added to the page. This grants complete control over the output and its presentation.
# Stream endpoint that generates sqrt(i) and yields it as a string @app.route("/stream") def stream(): def generate(): for i in range(500): yield f"{math.sqrt(i)}\n" time.sleep(1) return app.response_class(generate(), mimetype="text/plain")
<!-- Utilize JavaScript to handle streaming data updates --> <script> // Retrieve latest and historical values from streamed endpoint xhr.open("GET", "{{ url_for('stream') }}"); xhr.send(); var latest = document.getElementById("latest"); var output = document.getElementById("output"); var position = 0; function handleNewData() { // Split response, retrieve new messages, and track position var messages = xhr.responseText.split("\n"); messages.slice(position, -1).forEach(function (value) { latest.textContent = value; // Update latest value var item = document.createElement("li"); item.textContent = value; output.appendChild(item); }); position = messages.length - 1; } // Periodically check for new data and stop when stream ends var timer; timer = setInterval(function () { handleNewData(); if (xhr.readyState == XMLHttpRequest.DONE) { clearInterval(timer); latest.textContent = "Done"; } }, 1000); </script>
Using an Iframe** Approach
Alternatively, an iframe can display streamed HTML output. While initially easier to implement, it introduces disadvantages such as increased resource usage and limited styling options. Nonetheless, it can be useful for certain scenarios.
# Stream endpoint that generates html output @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=math.sqrt(i)) sleep(1) return app.response_class(generate())
<!-- Using an iframe for displaying streamed HTML --> <p>This is all the output:</p> <iframe src="{{ url_for("stream") }}"></iframe>
Conclusion
Whether utilizing JavaScript or iframes, Flask allows for the integration of real-time data streaming into templated web pages. These techniques enable the dynamic display of ever-changing data, providing a more engaging and real-time user experience.
The above is the detailed content of How to Display Real-time Data Streamed from a Flask View?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Fastapi ...

Using python in Linux terminal...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

About Pythonasyncio...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...
