Home >Web Front-end >JS Tutorial >How Can I Display Real-Time Data Streamed from a Flask View?

How Can I Display Real-Time Data Streamed from a Flask View?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 09:43:07625browse

How Can I Display Real-Time Data Streamed from a Flask View?

Displaying Data Streamed from a Flask View in Real Time

In Flask, streaming data from a view is straightforward. However, it's not possible to dynamically update an HTML template with this stream.

JavaScript and XMLHttpRequest

One solution is to use JavaScript and XMLHttpRequest. We can:

  1. Use XMLHttpRequest to establish a connection with the endpoint streaming the data.
  2. Periodically read from the stream until completion.
  3. Update the HTML directly with the received data.

Example:

# App
app = flask.Flask(__name__)

# Streaming view
@app.route('/')
def index():
    def generate():
        # Simulate data generation
        for i in range(500):
            yield str(i) + '<br/>\n'
    return flask.Response(generate(), mimetype='text/html')

# Run the app
app.run(debug=True)
<!-- Template -->
<p>Latest output: <span>

Using an Iframe

Another approach involves using an iframe to display streaming HTML output. Although this allows for styling flexibility and other advantages, it also introduces downsides:

  • Higher resource usage
  • Separate document, harder to integrate seamlessly
  • Potential scrolling issues with long output

Example:

index.html (Main Template)

<p>All output:</p>
<iframe src=&quot;{{ url_for('stream') }}&quot;></iframe>

Streaming View

@app.route('/stream')
def stream():
    @stream_with_context
    def generate():
        yield '<link rel=stylesheet href=&quot;{{ url_for('static', filename='stream.css') }}&quot;>'
        for i in range(500):
            yield '<p>{{ i }}: {{ s }}</p>\n'.format(i=i, s=math.sqrt(i))
            sleep(1)

stream.css (Optional Stylesheet)

body {
  font-family: sans-serif;
}
p {
  margin-bottom: 10px;
}

By utilizing either the JavaScript/XMLHttpRequest or the iframe methods, you can effectively display streamed data from your Flask view and maintain updates in real time.

The above is the detailed content of How Can I Display Real-Time Data Streamed from a Flask View?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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