-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
105 lines (77 loc) · 2.17 KB
/
server.py
File metadata and controls
105 lines (77 loc) · 2.17 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# author: oskar.blom@gmail.com
#
# Make sure your gevent version is >= 1.0
import gevent
from gevent.wsgi import WSGIServer
from gevent.queue import Queue
from flask import Flask, Response, request
import flask
import json
# SSE "protocol" is described here: http://mzl.la/UPFyxY
class ServerSentEvent(object):
def __init__(self, data):
self.data = data
self.event = None
self.id = None
self.desc_map = {
self.data: "data",
self.event: "event",
self.id: "id"
}
def encode(self):
if not self.data:
return ""
lines = ["%s: %s" % (v, k)
for k, v in self.desc_map.items() if k]
return "%s\n\n" % "\n".join(lines)
app = Flask(__name__)
subscriptions = []
datadict = {}
# Client code consumes like this.
@app.route("/")
def index():
return(flask.render_template("index.html",
value_ids=datadict))
@app.route("/debug")
def debug():
substring = "Currently %d subscriptions" % len(subscriptions)
html = """
<html>
<body>
{}</br>
{}
</body>
</html>
""".format(substring, str(datadict))
return html
@app.route('/update', methods=['POST'])
def update(*args, **kwargs):
j = json.loads(request.data)
for i in j:
datadict[i['id']] = i
print(datadict)
def notify():
msg = json.dumps(j)
for sub in subscriptions[:]:
sub.put(msg)
gevent.spawn(notify)
return json.dumps(dict(result="ok"))
@app.route("/subscribe")
def subscribe():
def gen():
q = Queue()
subscriptions.append(q)
try:
while True:
result = q.get()
ev = ServerSentEvent(str(result))
yield ev.encode()
except GeneratorExit: # Or maybe use flask signals
subscriptions.remove(q)
return Response(gen(), mimetype="text/event-stream")
if __name__ == "__main__":
app.debug = True
server = WSGIServer(("", 5000), app)
server.serve_forever()
# Then visit http://localhost:5000 to subscribe
# and send messages by visiting http://localhost:5000/publish