Home >Web Front-end >JS Tutorial >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:
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:
Example:
index.html (Main Template)
<p>All output:</p> <iframe src="{{ url_for('stream') }}"></iframe>
Streaming View
@app.route('/stream') def stream(): @stream_with_context def generate(): yield '<link rel=stylesheet href="{{ url_for('static', filename='stream.css') }}">' 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!