1

I am trying to stream yielded values in real time to HTML using flask and JavaScript.I would like to stream and display the values without any delay as soon as they are yielded from flask. However, I am currently not able to get the data displayed on the HTML side.

This is the Python Flask code:

from flask import Flask, render_template
import time

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/stream_time')
def stream():
    def generate():
        t=time.time()
        yield '{}\n'.format(time)
    return app.response_class(generate(), mimetype='text/plain')

app.run

The HTML/JS code to display and update the values in real time:

<p>This is the current value: <span id="latest_value"></span></p>
<script>
    var latest = document.getElementById('latest_value');

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '{{ url_for('stream') }}');
    xhr.send();

    var message = xhr.responseText.split('\n');
    latest.textContent = message;
</script>

Currently, I am not getting any values displayed on the page and I would like this to update on the field in real time.What am I doing wrong and how do i fix this?

5
  • do you get any error when you run flask in console ? Do you get any error in JavaScript console in web broweser ?
    – furas
    Commented Apr 23, 2020 at 23:59
  • do you can see stream when you open it directly in web browser http://your_domain.com/stream_time
    – furas
    Commented Apr 24, 2020 at 0:01
  • I thing it will not work - original version in tutorials yields images MJPEG which browser treads in special way and it can recognize where is end of one frame and update image. Your code yields strings all time and AJAX may treads it as one string and wait for end of this string - not as separated values - but yield never ends send text. Server may have to send text in normal way and JavaScript may have to run loop which get new text.
    – furas
    Commented Apr 24, 2020 at 0:06
  • BTW: JavaScript may run asynchronously and after running send() it may not wait for response and execute next line before it get response. You may have to use xhr.onload = function () {...} to run code when it get response.
    – furas
    Commented Apr 24, 2020 at 0:16
  • BTW: when I check JavaScript console in web browser I see error - it seems it has problem with \n in xhr.responseText.split(). To test code in JavaScript you can use alert() or console.log(text) (at least in Firefox)
    – furas
    Commented Apr 24, 2020 at 0:17

1 Answer 1

2

JavaScript works asynchronously and after running send() it doesn't wait for response and it executes next line before it gets response with text.

To get one response you have to use xhr.onload (before send()) to define function which xhr will run when it gets response

 xhr.onload = function () {
    latest.textContent = xhr.responseText;
 }

 xhr.send()

Minimal working code

from flask import Flask, render_template_string
import time

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<p>This is the current value: <span id="latest_value"></span></p>
<script>
    var latest = document.getElementById('latest_value');

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '{{ url_for('stream') }}');

    xhr.onload = function() {
        latest.textContent = xhr.responseText;
    }

    xhr.send();

    /* this lines will give `><` because `xhr.responseText` is still empty */
    /* you can remove these lines */
    console.log(">" + xhr.responseText + "<")
    latest.textContent = ">" + xhr.responseText + "<";

</script>''')

@app.route('/stream_time')
def stream():
    def generate():
        current_time = time.strftime("%H:%M:%S\n")
        print(current_time)
        yield current_time

    return app.response_class(generate(), mimetype='text/plain')

app.run()

To update periodically text in browser you have to first use while loop in generator to send many values.

For test I use also time.sleep(1) to send less data

    def generate():
        while True:
            current_time = time.strftime("%H:%M:%S\n")
            print(current_time)
            yield current_time
            time.sleep(1)

Now in JavaScript you have to use xhr.onreadystatechange to assign function which will update text on page when it gets new data from server

xhr.onreadystatechange = function() {
    var all_messages = xhr.responseText.split('\n');
    last_message = all_messages.length - 2
    latest.textContent = all_messages[last_message]
}

Because xhr.responseText ends with \n so split('\n') creates empty message as last element on list all_messages so I use length - 2 instead of length - 1


Minimal working code

from flask import Flask, render_template_string
import time

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''<p>This is the current value: <span id="latest_value"></span></p>
<script>

    var latest = document.getElementById('latest_value');

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '{{ url_for('stream') }}');

    xhr.onreadystatechange = function() {
        var all_lines = xhr.responseText.split('\\n');
        last_line = all_lines.length - 2
        latest.textContent = all_lines[last_line]

        if (xhr.readyState == XMLHttpRequest.DONE) {
            /*alert("The End of Stream");*/
            latest.textContent = "The End of Stream"
        }
    }

    xhr.send();

</script>''')

@app.route('/stream_time')
def stream():
    def generate():
        while True:
            current_time = time.strftime("%H:%M:%S\n")
            print(current_time)
            yield current_time
            time.sleep(1)

    return app.response_class(generate(), mimetype='text/plain')

app.run()

BTW: because I used render_template_string(html) instead of render_template(filename) so I had to use \\n instead of \n

1
  • thanks alot @furas, let me try this and get back to you. Commented Apr 24, 2020 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.