Created
August 11, 2022 17:47
-
-
Save Park-Developer/9f99a9c0638926724e136c863ecccdfe to your computer and use it in GitHub Desktop.
update periodically text in browser using ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
https://stackoverflow.com/questions/61398680/updating-streamed-data-from-flask-in-real-time