You can send data in response, but you cannot dynamically update the template as you describe. The template is created once on the server side, and then sent to the client. You will need to use JavaScript to read the streaming response and output the data on the client side.
Use XMLHttpRequest to query the endpoint that will transmit the data. Then periodically read the thread until it is executed.
This example uses a very simple message format: one line of data followed by a new line. Of course, you can get as complicated in parsing as you want if there is a way to identify each message. For example, you can return a JSON object and decode it on the client.
from time import sleep from flask import Flask, render_template from math import sqrt app = Flask(__name__) @app.route('/') def index():
<p>This is the latest output: <span id="latest"></span></p> <p>This is all the output:</p> <ul id="output"></ul> <script> 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() { </script>
davidism
source share