Skip to content

Instantly share code, notes, and snippets.

@fourdollars
Created October 26, 2020 13:31

Revisions

  1. fourdollars created this gist Oct 26, 2020.
    31 changes: 31 additions & 0 deletions app.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    #!/usr/bin/env python

    import time
    from flask import Flask, render_template, Response

    app = Flask(__name__)

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

    def get_message():
    '''this could be any function that blocks until data is ready'''
    time.sleep(1.0)
    s = time.ctime(time.time())
    return s

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

    @app.route('/stream')
    def stream():
    def eventStream():
    while True:
    # wait for source data to be available, then push it
    yield 'data: {}\n\n'.format(get_message())
    return Response(eventStream(), mimetype="text/event-stream")

    if __name__ == "__main__":
    app.run()
    15 changes: 15 additions & 0 deletions sse.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <script>
    var es = new EventSource("{{ url_for('stream') }}");
    es.onmessage = function(e) {
    console.log("" + e.data + " from " + e.origin);
    };
    </script>
    </head>
    <body>
    <h1>SSE test</h1>
    </body>
    </html>