/
api_routes.py
195 lines (165 loc) · 6.64 KB
/
api_routes.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
from flask import Blueprint, request, abort, json, jsonify
from datetime import datetime
import bustracker as btr
import currentdata
import logging, sys
import os
import inspect
import pprint
logging.basicConfig(filename='ignore/bustracker.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)
api_routes = Blueprint("api", __name__)
def wrap_exceptions(fn):
def wrapped_fn():
traceback = None
try:
return fn()
except Exception as exc:
(_, __, traceback) = sys.exc_info()
frame = inspect.getinnerframes(traceback)[-1][0]
frame_locals = frame.f_locals
logger.exception("", exc_info=exc)
pprint.pprint(frame_locals)
finally:
del locals()["traceback"]
if os.environ.get("MODE") == "prod":
return fn
wrapped_fn.__name__ = fn.__name__
return wrapped_fn
@api_routes.route("/updates")
@wrap_exceptions
def updates():
vehicle_ids = request.args.get("vehicles", "")
vehicle_idlist = vehicle_ids.split(',')
if vehicle_ids:
vehicle_preds = currentdata.current_data.getPredsForVehicles(vehicle_idlist)
else:
vehicle_preds = None
stop_ids = request.args.get("stops", "")
stop_idlist = stop_ids.split(',')
if stop_ids:
stops = currentdata.current_data.getPredsForStops(stop_idlist)
else:
stops = None
route_ids = request.args.get("routes", "")
active_shapes = []
if route_ids:
route_idlist = route_ids.split(',')
logger.info('routes: ' + route_ids)
vehicles = currentdata.current_data.getVehiclesOnRoutes(route_idlist)
for veh in vehicles:
#shape_id = btr.tripshapedict.get(veh.get('trip_id'), '')
shape_id = veh.get('shape_id','')
# if shape_id == '': #Unscheduled trip. Try to get shape_id by matching direction and destination
# shape_id = btr.getShapeForUnschedTrip(veh.get('route_id', ''),
# veh.get('direction', ''),
# veh.get('destination', ''))
if shape_id:
active_shapes.append(shape_id)
#path = btr.shapepathdict.get(shape_id, [])
veh_preds = currentdata.current_data.getPredsForOneVehicle(veh.get('id'), veh.get('trip_id'))
if len(veh_preds) == 0:
veh['timepoints'] = [{'lat' : veh.get('lat'),
'lon' : veh.get('lon'),
'time' :veh.get('timestamp')}]
else:
veh['timepoints'] = btr.getTimepoints(veh.get('lat'),veh.get('lon'),
veh.get('timestamp'), shape_id,
veh_preds)
else:
veh['timepoints'] = [{'lat' : veh.get('lat'),
'lon' : veh.get('lon'),
'time' :veh.get('timestamp')}]
else:
vehicles = []
active_shapes = sorted(list(set(active_shapes)))
since = request.args.get("since", "") # Timestamp in seconds
# if since:
# when = long(since)
# vehicles = [veh for veh in vehicles if int(veh["timestamp"]) > when]
now_stamp = long(btr.time.time())
return jsonify(vehicles = vehicles,
active_shapes = active_shapes,
stamp = now_stamp,
stops = stops,
vehicle_preds = vehicle_preds)
@api_routes.route("/routes")
@wrap_exceptions
def all_routes():
#the route_ids are in a reasonable order for a user to choose from
routes = btr.routeinfodict.values()
routes.sort(key = lambda x : x['sort_order'])
#route_names = dict([(route_id, btr.routenamesdict[route_id]) for route_id in route_ids])
return jsonify({'data': routes})
@api_routes.route("/routeinfo")
@wrap_exceptions
def route_info():
if "routes" not in request.args:
abort(404)
routes = request.args.get("routes", "")
route_ids = routes.split(",")
response = {}
#stop_ids = []
for route_id in route_ids:
try:
shape_ids = btr.routeshapedict[route_id]
shape2path = dict([(shid, btr.shapepathdict.get(shid)) for shid in
shape_ids])
paths = btr.pathReducer([btr.shapepathdict.get(shape_id) for shape_id
in shape_ids])
stop_ids = btr.routestopsdict.get(route_id)
stops = [btr.stopinfodict.get(stop_id) for stop_id in stop_ids]
routename = btr.routenamesdict.get(route_id)
parent_stops = btr.getParentsForStops(stop_ids)
response[route_id] = {
"shape_ids": shape_ids,
"shape2path": shape2path,
"paths": paths,
"stop_ids": stop_ids,
"stops": stops,
"routename": routename,
"parent_stops": parent_stops
}
except KeyError:
er = sys.exc_info()
logger.error(er)
response[route_id] = None
return jsonify(routes=response)
@api_routes.route("/locationinfo")
@wrap_exceptions
def location_info():
if "lat" not in request.args or "lon" not in request.args:
abort(401)
lat = float(request.args.get('lat', 40))
lon = float(request.args.get('lon', -71))
radius = float(request.args.get('radius', 800))
numstops = int(request.args.get('numstops', 15))
nearby_stops = btr.getNearbyStops(lat, lon, numstops, radius)
routeidlist = btr.getRoutesForStops([stop.get('stop_id') for stop in nearby_stops])
parent_stops = btr.getParentsAmongStops([s['stop_id'] for s in nearby_stops])
return jsonify(stops = nearby_stops,
route_ids = routeidlist,
parent_stops = parent_stops)
@api_routes.route("/alerts")
@wrap_exceptions
def alerts():
alerts = btr.getAllAlertsGTFS()
return jsonify(alerts = alerts)
@api_routes.route("/rectangle")
@wrap_exceptions
def rectangle():
'''
get all stops inside a rectangle with given SW and NE corners
'''
try:
swlat = float(request.args["swlat"])
swlon = float(request.args["swlon"])
nelat = float(request.args["nelat"])
nelon = float(request.args["nelon"])
except KeyError, ValueError:
er = sys.exc_info()
logger.error(er)
abort(401)
stops, parent_stops = btr.getStopsInRectangle(swlat, swlon, nelat, nelon)
return jsonify(stops = stops,
parent_stops = parent_stops)