Skip to content

Instantly share code, notes, and snippets.

@helambuapps
Created June 10, 2020 10:08
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 helambuapps/05c283e24ef3796fea07265842dfe2c7 to your computer and use it in GitHub Desktop.
Save helambuapps/05c283e24ef3796fea07265842dfe2c7 to your computer and use it in GitHub Desktop.
Flask Server Sent Event Sample
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