-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
305 lines (229 loc) · 7.25 KB
/
api.py
File metadata and controls
305 lines (229 loc) · 7.25 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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# I mean, this implementation sucks big time, but it works so what?
import json
import contextlib
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.exceptions import HTTPException
import sqlite3
import aiosqlite
from config import config
class Network:
stations = None
vehicles = None
@staticmethod
def from_row(row):
n = Network()
meta = json.loads(row['meta'])
n.id = row['tag']
n.name = meta.pop('name')
n.location = {
'latitude': meta.pop('latitude'),
'longitude': meta.pop('longitude'),
'city': meta.pop('city'),
'country': meta.pop('country'),
}
n.href = f'{config.prefix}/networks/{n.id}'
# over-set anything else present in meta
for k, v in meta.items():
setattr(n, k, v)
return n
def dump(self):
rpr = dict(self.__dict__)
if self.stations:
rpr['stations'] = [s.dump() for s in self.stations]
if self.vehicles:
rpr['vehicles'] = [v.dump() for v in self.vehicles]
return rpr
class Station:
@staticmethod
def from_row(row):
n = Station()
stat = json.loads(row['stat'])
row.update(stat)
n.id = row['hash']
n.name = row['name']
n.latitude = row['latitude']
n.longitude = row['longitude']
n.timestamp = row['timestamp'] + 'Z'
n.free_bikes = row['bikes']
n.empty_slots = row['free']
n.extra = row['extra']
return n
def dump(self):
return self.__dict__
class Vehicle:
@staticmethod
def from_row(row):
n = Vehicle()
stat = json.loads(row['stat'])
row.update(stat)
n.id = row['hash']
n.latitude = row['latitude']
n.longitude = row['longitude']
n.timestamp = row['timestamp'] + 'Z'
n.extra = row['extra']
n.kind = row['kind']
return n
def dump(self):
return self.__dict__
def named_params(handler):
async def _handler(request):
args = request.path_params
r = await handler(request, ** args)
return r
return _handler
# Good enough
def ffilter(obj, query, prefix=''):
def deep_merge(* dicts):
""" naive recursive of dicts and only dicts """
def merge(d1, d2):
r = dict(d1)
for k, v in d2.items():
if k in r:
if isinstance(r[k], dict):
r[k] = merge(r[k], v)
else:
r[k] = v
else:
r[k] = v
return r
res = {}
for d in dicts:
res = merge(res, d)
return res
result = type(obj)()
def _filter(obj, query, target):
if not query:
return
_query = query.split('.', 1)
h, r = _query.pop(0), ''.join(_query)
if isinstance(obj, dict):
if h not in obj:
return
body = obj[h]
if r == "":
target[h] = body
return
if h not in target:
target[h] = type(obj[h])()
_filter(body, r, target[h])
elif isinstance(obj, list):
body = []
for thing in obj:
t = {}
_filter(thing, h + '.' + r, t)
body.append(t)
if len(target) == 0:
target += body
else:
for i in range(len(target)):
target[i] = deep_merge(target[i], body[i])
# Define max to bail early
if query.count(',') > 25 or query.count('.') > 25:
raise Exception()
for q in map(str.strip, query.split(',')):
q = q.removeprefix(prefix + '.')
_filter(obj, q, result)
return result
async def networks(request):
db = request.app.db
cur = await db.execute('SELECT * FROM networks ORDER BY tag')
rows = await cur.fetchall()
networks = [Network.from_row(r).dump() for r in rows]
response = list(networks)
fields = request.query_params.get('fields')
if fields:
try:
response = ffilter(response, fields, 'networks')
except:
raise HTTPException(status_code=400)
return JSONResponse({'networks': response})
async def network(request, uid=None):
db = request.app.db
cur = await db.execute("""
SELECT * FROM networks
WHERE tag = ?
LIMIT 1
""", (uid, ))
net = await cur.fetchone()
if not net:
raise HTTPException(status_code=404)
cur = await db.execute("""
SELECT s.*
FROM stations s
WHERE network_tag = ?
AND hash IN (
SELECT value FROM networks
JOIN json_each(networks.stations) ON networks.tag = ?
)
ORDER BY hash
""", (uid, uid, ))
stations = await cur.fetchall()
fields = request.query_params.get('fields')
network = Network.from_row(net)
network.stations = [Station.from_row(row) for row in stations]
# Do not include 'vehicles' on the response if no vehicles at all
if fields and 'vehicles' in fields:
cur = await db.execute("""
SELECT v.*
FROM vehicles v
WHERE network_tag = ?
AND hash IN (
SELECT value FROM networks
JOIN json_each(networks.vehicles) ON networks.tag = ?
)
ORDER BY hash
""", (uid, uid, ))
vehicles = await cur.fetchall()
if vehicles:
network.vehicles = [Vehicle.from_row(row) for row in vehicles]
response = network.dump()
if fields:
try:
response = ffilter(response, fields, 'network')
except:
raise HTTPException(status_code=400)
return JSONResponse({'network': response})
async def station(request, uid=None, suid=None):
if not uid or not suid:
raise HTTPException(status_code=400)
db = request.app.db
cur = await db.execute("""
SELECT * FROM stations
WHERE network_tag = ?
AND hash = ?
""", (uid, suid, ))
row = await cur.fetchone()
if not row:
raise HTTPException(status_code=404)
station = Station.from_row(row).dump()
fields = request.query_params.get('fields')
if fields:
try:
station = ffilter(station, fields, 'station')
except:
raise HTTPException(status_code=400)
return JSONResponse({"station": station})
async def home(request):
return JSONResponse({'hello': 'world'})
from citybikes.db.asyncio import CBD, get_session, migrate
@contextlib.asynccontextmanager
async def lifespan(app):
async with get_session(config.db_uri) as db:
assert await migrate(db)
app.db = CBD(db)
yield
routes = [
Route('/', home),
Route('/networks', networks),
# XXX this until we fix ROOT_PATH uvicorn/gunicorn NONSENSE
Route('/networks/', networks),
Route('/networks/{uid}', named_params(network)),
Route('/networks/{uid}/stations/{suid}', named_params(station)),
]
app = Starlette(
debug=config.debug,
routes=routes,
lifespan=lifespan,
)