Created
October 26, 2020 13:31
-
-
Save fourdollars/c4278b6addbae3482fa2c514ecb7e43d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/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() |
This file contains hidden or 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
<!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