Skip to content

Instantly share code, notes, and snippets.

@ByK95
Forked from jelmervdl/index.html
Created January 23, 2020 09:50
Show Gist options
  • Save ByK95/8c48eddcf71c920e1c43b8fd8c299e3e to your computer and use it in GitHub Desktop.
Save ByK95/8c48eddcf71c920e1c43b8fd8c299e3e to your computer and use it in GitHub Desktop.
Pure Python & Flask server-side event source
<script>
var stream = new EventSource('/api/stream');
stream.onmessage = function(e) {
console.info(e.data);
};
</script>
from queue import Queue
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
queue = Queue()
def event_stream():
while True:
# Question: how to break out of this loop when the app is killed?
message = queue.get(True)
print("Sending {}".format(message))
yield "data: {}\n\n".format(message)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/api/stream')
def stream():
return flask.Response(event_stream(), mimetype="text/event-stream")
@app.route('/api/post', methods=['GET'])
def api_parse_sentence():
queue.put(request.args.get('sentence'))
return "OK"
if __name__ == '__main__':
app.run(threaded=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment