Table of Contents
Displaying Data Streamed from a Flask View in Real Time
Home Backend Development Python Tutorial How to Display Real-time Data Streamed from a Flask View?

How to Display Real-time Data Streamed from a Flask View?

Dec 08, 2024 pm 10:47 PM

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")
Copy after login
<!-- 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>
Copy after login

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())
Copy after login
<!-- Using an iframe for displaying streamed HTML -->
<p>This is all the output:</p>
<iframe src="{{ url_for("stream") }}"></iframe>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

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)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

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

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

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...

See all articles