-
Notifications
You must be signed in to change notification settings - Fork 81
/
api.py
73 lines (60 loc) · 1.73 KB
/
api.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
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
# -*- coding: utf-8 -*-
import json, time
from flask import Flask, Response, jsonify, render_template, request
import gevent
from gevent.wsgi import WSGIServer
from gevent.queue import Queue
app = Flask(__name__)
subscriptions = []
@app.route('/health/', methods=['GET'])
def health():
return '200 OK'
@app.route('/', methods=['GET'])
def home():
return render_template('test.html')
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.iteritems() if k]
return "%s\n\n" % "\n".join(lines)
@app.route("/publish/epoch/end/", methods=['POST'])
def publish():
payload = request.form.get('data')
try:
data = json.loads(payload)
except:
return {'error':'invalid payload'}
def notify():
msg = str(time.time())
for sub in subscriptions[:]:
sub.put(payload)
gevent.spawn(notify)
return "OK"
@app.route("/subscribe/epoch/end/")
def subscribe():
def gen():
q = Queue()
subscriptions.append(q)
try:
while True:
result = q.get()
event = ServerSentEvent(str(result))
yield event.encode()
except GeneratorExit:
subscriptions.remove(q)
return Response(gen(), mimetype="text/event-stream")
if __name__ == "__main__":
app.debug = True
server = WSGIServer(("", 9000), app)
server.serve_forever()