-
-
Save ByK95/8c48eddcf71c920e1c43b8fd8c299e3e to your computer and use it in GitHub Desktop.
Pure Python & Flask server-side event source
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
<script> | |
var stream = new EventSource('/api/stream'); | |
stream.onmessage = function(e) { | |
console.info(e.data); | |
}; | |
</script> |
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
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