Created
March 25, 2023 04:36
-
-
Save python273/ee57eae940bebd406ad6a53cec98c955 to your computer and use it in GitHub Desktop.
Flask SSE demo
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
from flask import Flask, Response | |
import time | |
import json | |
app = Flask(__name__) | |
@app.route('/') | |
def index(): | |
return Response(''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Flask SSE Example</title> | |
</head> | |
<body> | |
<div id="output"></div> | |
<script> | |
var outputEl = document.getElementById('output'); | |
var source = new EventSource('/sse'); | |
source.onmessage = function(event) { | |
outputEl.innerText += JSON.parse(event.data).chunk; | |
}; | |
// don't auto restart connection | |
source.onerror = function(event) { source.close(); }; | |
</script> | |
</body> | |
</html> | |
''', mimetype='text/html') | |
@app.route('/sse') | |
def sse(): | |
def _stream(): | |
for i in range(10): | |
data = {'chunk': f'{i}\n'} | |
yield 'data: {}\n\n'.format(json.dumps(data)) | |
time.sleep(1) | |
return Response(_stream(), mimetype='text/event-stream') | |
if __name__ == '__main__': | |
app.run(threaded=True, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment