Implement html5 Server-Sent Events (SSE) with python flask (a server-side clock demo)

Python code

from flask import Flask, Response
from datetime import datetime
import time

app = Flask(__name__)


# a generator with yield expression
def gen_date_time():
    while True:
        time.sleep(1)
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # DO NOT forget the prefix and suffix
        yield 'data: %s\n\n' % now


@app.route('/sse_demo')
def sse_demo():
    return Response(
        gen_date_time(),  # gen_date_time() is an Iterable
        mimetype='text/event-stream'  # mark as a stream response
    )


HTML = '''<!DOCTYPE html>
<html>
<body>
    Server side clock: <span id="clock"></span>
    <script>
        var source = new EventSource("/sse_demo");
        source.onmessage = function (event) {
            document.getElementById("clock").innerHTML = event.data;
        };
    </script>
</body>
</html>'''


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


app.run()

Points to note

  • Use a generator like gen_date_time to populate the data you want to send to the client continuously.
  • Notice yield 'data: %s\n\n' % now in the generator, the prefix data: and the suffix \n\n are necessary.
  • mimetype of the stream API must be text/event-stream

Test it

  • Run the python code above.
  • Open your browser and enter http://127.0.0.1:5000/
  • In the browser, you will see something like Server side clock: 2022-06-26 20:21:40. It will refresh every second.
Posted on 2022-06-26