Overall, my goal is to convert several console-based Python scripts into Flask, so they can be deployed as webapps.
Current challenge: converting a series of console print()
messages into a streaming update in the HTML page.
It seems like these messages could be appended to a single string array, that is returned and shown on index.html. But there needs to be a way to trigger the HTML to update from the server side, since the user isn't going to supply any input.
I cobbled together some scripts from Streaming data with Python and Flask and Display data streamed from a Flask view as it updates. It doesn't show the messages, though, just "nothing received yet."
app.py:
from flask import Flask, Response, jsonify, render_template, request, redirect, url_for
import time
from time import sleep
app = Flask(__name__)
@app.route('/')
def index():
if request.headers.get('accept') == 'text/event-stream':
messages = []
def script():
#a lot of code goes here
yield "data: Part A completed.\n\n"
#more code
sleep(10)
yield "data: Part B completed.\n\n"
#more code
sleep(10)
yield "data: Part C completed.\n\n"
return Response(script(), content_type='text/event-stream')
return redirect(url_for('static', filename='index.html'))
if __name__ == '__main__':
app.run()
index.html:
<!doctype html>
<title>Messages</title>
<style>
#messages {
text-align: left;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
if (!!window.EventSource) {
var source = new EventSource('/');
source.onmessage = function(e) {
$("#messages").text(e.data);
}
}
</script>
<div id="messages">nothing received yet</div>
UPDATED to include Sergey's notes below