Created
June 10, 2020 10:08
-
-
Save helambuapps/05c283e24ef3796fea07265842dfe2c7 to your computer and use it in GitHub Desktop.
Flask Server Sent Event Sample
This file contains 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
import flask | |
from random import randint | |
app = flask.Flask(__name__) | |
box = "" | |
@app.route('/subscribe') | |
def subscribe(): | |
def get_subscribtion_message(): | |
global box | |
while True: | |
if box: | |
data = box | |
box = "" | |
yield data | |
return flask.Response(get_subscribtion_message(), content_type='text/event-stream') | |
@app.route('/notify') | |
def notify(): | |
global box | |
r = randint(0, 999999) | |
box = f"data: Random number = {r}\n\n" | |
return f"Published {r}" | |
@app.route('/') | |
def root(): | |
return """ | |
<script> | |
var es = new EventSource('/subscribe'); | |
es.onmessage = function(e) { | |
console.log(e.data); | |
} | |
es.onerror = function(e) { | |
console.error(e); | |
} | |
</script> | |
""" | |
app.run(debug=True, threaded=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment