-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
78 lines (64 loc) · 2.21 KB
/
server.py
File metadata and controls
78 lines (64 loc) · 2.21 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# author: jiehua233@gmail.com
#
import falcon
import redis
import ujson as json
import config
from wsgiref import simple_server
def validate_direction(req, resp, resource, params):
direction = params.get("direction")
if direction == "positive":
params["direction"] = 0
elif direction == "negative":
params["direction"] = 1
else:
raise falcon.HTTPBadRequest("Error", "Illegal direction")
class BusResource(object):
def __init__(self):
rpool = redis.ConnectionPool(**config.REDIS)
self.rds = redis.StrictRedis(connection_pool=rpool)
@falcon.before(validate_direction)
def on_get(self, req, resp, direction):
resp.status = falcon.HTTP_200
result = {"c": 0, "d": {}, "msg": ""}
data = self.rds.get(config.REDISKEY)
if data:
bus_data = json.loads(data)
result["d"] = self.pack_data(direction, bus_data["content"])
result["msg"] = "Success"
else:
result["c"] = -1
result["msg"] = "No bus data"
resp.body = json.dumps(result)
def pack_data(self, direction, bus):
d = bus[direction]
result = {
"busLine": {
"lineName": d['busLine']['lineName'],
"firstTime": d['busLine']['firstTime'],
"lastTime": d['busLine']['lastTime'],
"strPlatName": d['busLine']['strPlatName'],
"endPlatName": d['busLine']['endPlatName'],
"totalPlat": d['busLine']['totalPlat'],
"stationNames": d['busLine']['stationNames'],
"flagSubway": d['busLine']['flagSubway'],
},
"busTerminal": [],
}
for b in d["busTerminal"]:
result["busTerminal"].append({
"stationSeq": b["stationSeq"],
"adflag": b["adflag"],
})
return result
app = falcon.API()
bus = BusResource()
app.add_route("/{direction}", bus)
if __name__ == "__main__":
print "Starting server on ", config.bind
host, port = config.bind.split(":")
httpd = simple_server.make_server(host, int(port), app)
httpd.serve_forever()