Repository navigation
Expand file tree
/
Copy pathapi_v1.py
More file actions
144 lines (107 loc) · 3.25 KB
/
Copy pathapi_v1.py
File metadata and controls
144 lines (107 loc) · 3.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
# 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
import os
from config import config
class Network:
stations = None
@staticmethod
def from_row(i, row):
n = Network()
meta = json.loads(row['meta'])
n.id = i
n.tag = row['tag']
n.name = meta.pop('name')
n.city = meta.pop('city')
n.lat = int(meta.pop('latitude') * 1E6)
n.lng = int(meta.pop('longitude') * 1E6)
n.radius = 5000
n.url = '%s/%s.json' % (config.endpoint, row['tag'])
# 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]
return rpr
class Station:
@staticmethod
def from_row(i, row):
n = Station()
stat = json.loads(row['stat'])
row.update(stat)
n.id = i
n.idx = i
n.name = row['name']
n.lat = int(row['latitude'] * 1E6)
n.lng = int(row['longitude'] * 1E6)
n.timestamp = row['timestamp'] + 'Z'
n.bikes = row['bikes']
n.free = row['free']
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
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(i, r).dump() for i, r in enumerate(rows)]
return JSONResponse(networks)
async def network(request, uid=None):
db = request.app.db
cur = await db.execute("""
SELECT * FROM networks
WHERE tag = ?
LIMIT 1
""", (uid, ))
row = await cur.fetchone()
if not row:
raise HTTPException(status_code=404)
# XXX Check perf on both of these
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, ))
rows = await cur.fetchall()
network = Network.from_row(0, row)
network.stations = [Station.from_row(i, row) for i, row in enumerate(rows)]
return JSONResponse([s.dump() for s in network.stations])
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.json', networks),
Route('/{uid}.json', named_params(network)),
]
app = Starlette(
debug=config.debug,
routes=routes,
lifespan=lifespan,
)