Skip to content

Instantly share code, notes, and snippets.

@fourdollars
Created October 26, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourdollars/c4278b6addbae3482fa2c514ecb7e43d to your computer and use it in GitHub Desktop.
Save fourdollars/c4278b6addbae3482fa2c514ecb7e43d to your computer and use it in GitHub Desktop.
#!/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()
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment