-
Notifications
You must be signed in to change notification settings - Fork 5
/
sse.py
46 lines (33 loc) · 1.27 KB
/
sse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Example of using server-sent events with Flask using gevent.
This can be run as-is using gevent's built-in WSGI server, or you can
run it with gunicorn as follows::
gunicorn -b 127.0.0.1:5000 -k gevent sse:app
If testing connections with a single browser, keep in mind that the
browser may have a setting to limit the number of persistent
connections per server. For example, in Firefox, there is a
``network.http.max-persistent-connections-per-server`` setting which
defaults to 6 (at least on my browser).
"""
import gevent
from gevent.pywsgi import WSGIServer
from gevent import monkey
monkey.patch_all()
from numpy import random
from flask import Flask, json, Response, render_template
app = Flask(__name__)
def event():
"""For something more intelligent, take a look at Redis pub/sub
stuff. A great example can be found here__.
__ https://github.com/jakubroztocil/chat
"""
while True:
yield 'data: ' + json.dumps(random.rand(1000).tolist()) + '\n\n'
gevent.sleep(0.2)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/stream/', methods=['GET', 'POST'])
def stream():
return Response(event(), mimetype="text/event-stream")
if __name__ == "__main__":
WSGIServer(('', 5000), app).serve_forever()