-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrun.py
301 lines (258 loc) · 9.06 KB
/
run.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
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
import json
import os
from sqlite3 import OperationalError
from glob import glob
from flask import Flask, request
from gtfspy import gtfs
from gtfspy import stats
from flask_runner import Runner
import settings
from flask_cors import CORS, cross_origin
if __name__ == '__main__':
# Development mode: run as main script.
DEBUG = True
else:
# Production mode. Currently under URL /transit/
BASE_URL = '/transit/'
app = Flask(__name__, static_url_path='')
CORS(app)
app.config.from_object(__name__)
# This provides a HTML toolbar that allows debugging, mainly
# profiling. The request must be HTML, minimal working thing is:
# return '<body>%s</body>'%json.dumps(...)
#from flask.ext.debugtoolbar import DebugToolbarExtension
#toolbar = DebugToolbarExtension(app)
@app.route("/")
@app.route("/dummy2")
def index():
return json.dumps({"url": str(request.url), "query_string": str(request.query_string)})
if not __name__ == '__main__':
# If in production: add a logging handler
import logging
from logging import FileHandler
file_handler = FileHandler('log/log.txt')
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
viz_cache = {}
def cache(func, *args, **kwargs):
"""
Parameters
----------
func: function
"""
name = func.func_name
args_ = hash(tuple(args))
kwargs_ = hash(tuple(kwargs.items()))
cache_key = (name, args_, kwargs_)
if cache_key not in viz_cache:
viz_cache[cache_key] = func(*args, **kwargs)
else:
print("found in cache")
return viz_cache[cache_key]
# Database filenames. Make a list of all filenames. Remove the
# common prefix. Save a cache of everything that needs to be sent to
# the server. This is re-generated every time this file is reloaded,
# and only then (but that is as often as it was before this was split
# out, too).
def find_dbfnames():
dbfnames = []
for sdir in settings.DB_DIRS:
# If is a regular file, just use this directly.
if os.path.isfile(sdir):
dbfnames.append(sdir)
continue
# Directories: all sub-directory sqlite files.
for cur_dir, subdirs, files in os.walk(sdir):
for ending in settings.DB_ENDINGS:
dbfnames.extend(glob(os.path.join(cur_dir, ending)))
dbfnames = list(set(dbfnames)) # remove any duplicates
# Remove common prefix
if len(dbfnames) == 1:
commonprefix = ""
else:
commonprefix = os.path.commonprefix(dbfnames)
dbfnames = [fname[len(commonprefix):] for fname in dbfnames]
# exclude tests:
dbfnames = sorted([e for e in dbfnames if "proc/test/" not in e])
valid_dbfnames = []
timezone_dict = {}
for dbf in dbfnames:
try:
timezone_dict[dbf] = gtfs.GTFS(commonprefix+dbf).get_timezone_string()
valid_dbfnames.append(dbf)
except OperationalError as e:
print("database " + dbf + " is not available due to: \n" + e.message)
data = {'dbfnames': valid_dbfnames,
'timezones': timezone_dict}
dbfname_cache = json.dumps(data)
return dbfnames, commonprefix, dbfname_cache
# Run finder function to set the needed variables.
dbfnames, commonprefix, dbfname_cache = find_dbfnames()
def get_dbfname(dbfname):
"""Return actual filename from user-provided filename.
This has two purposes
- Re-add the commonprefix which was removed above.
- Return None if the filename is not in `dbfnames`. We *have* to
check it against an authorized list, or else someone could open
any file on disk. We can either sanitize it, or we can only allow
ones in the list to be opened. We use the second option because
it is simpler and less error prone.
Of these, the second is the most important. Removing the common
prefix has the nice property that any attempt to open a dbfname that
does *not* use this function to sanitize input will fail (on good data)
"""
# TODO: O(N)
if dbfname not in dbfnames:
return None
return commonprefix + dbfname
@app.route("/databases")
def available_gtfs_dbs():
"""
Returns available databases and the timezone for each database.
These results are cached after the first request
"""
return dbfname_cache
# data = {'hsl-2015-04-24.sqlite':
# {
# start_time_ut : 0,
# end_time_ut : float("inf"),
# max_activity_hour_start_ut : 0,
# centroid_lat : 0,
# centroid_lon : 0
# }
# }
# database_names = ["hsl-2015-04-24.sqlite", "hsl-2015-07-12.sqlite"]
# return json.dumps(data)
@app.route("/trajectories")
def get_scheduled_trips_within_interval():
tstart = request.args.get('tstart', None)
tend = request.args.get('tend', None)
dbfname = get_dbfname(request.args.get('dbfname', None))
shapes = request.args.get('use_shapes', None)
if shapes == "1":
shapes = True
else:
shapes = False
if tstart:
tstart = int(tstart)
if tend:
tend = int(tend)
G = gtfs.GTFS(dbfname) # handles connections to database etc.
trips = G.get_trip_trajectories_within_timespan(start=tstart, end=tend, use_shapes=False)
return json.dumps(trips)
@app.route("/stats")
def get_gtfs_stats():
dbfname = get_dbfname(request.args.get('dbfname', None))
if not dbfname:
return json.dumps({})
G = gtfs.GTFS(dbfname)
data = stats.get_stats(G)
return json.dumps(data)
@app.route("/gtfsspan")
def get_start_and_end_time_ut():
dbfname = get_dbfname(request.args.get('dbfname', ""))
if dbfname is "null":
dbfname = ""
G = gtfs.GTFS(dbfname)
start, end = G.get_approximate_schedule_time_span_in_ut()
data = {
"start_time_ut": start,
"end_time_ut": end
}
return json.dumps(data)
@app.route("/tripsperday")
def get_trip_counts_per_day():
dbfname = get_dbfname(request.args.get('dbfname', None))
if not dbfname:
return json.dumps({})
g = gtfs.GTFS(dbfname)
data = g.get_trip_counts_per_day()
data_dict = {
"trip_counts": [int(c) for c in data["trip_counts"].values],
"dates": [str(date) for date in data["date_str"].values]
}
return json.dumps(data_dict)
@app.route("/stopcounts")
def view_stop_data():
#print request.args
tstart = int(request.args.get('tstart', None))
tend = int(request.args.get('tend', None))
dbfname = get_dbfname(request.args.get('dbfname', None))
G = gtfs.GTFS(dbfname) # handles connections to database etc.
stopdata = G.get_stop_count_data(tstart, tend)
return stopdata.to_json(orient="records")
# json.dumps(stopdata.to_dict("records"))
@app.route("/linkcounts")
def view_segment_data():
#print request.args
tstart = int(request.args.get('tstart', None))
tend = int(request.args.get('tend', None))
dbfname = get_dbfname(request.args.get('dbfname', None))
shapes = request.args.get('use_shapes', None)
if shapes == "1":
shapes = True
else:
shapes = False
G = gtfs.GTFS(dbfname) # handles connections to database etc.
data = G.get_segment_count_data(tstart, tend, use_shapes=shapes)
return json.dumps(data)
@app.route("/routes")
def view_line_data():
#print request.args
dbfname = get_dbfname(request.args.get('dbfname', None))
shapes = request.args.get('use_shapes', None)
if shapes == "1":
shapes = True
else:
shapes = False
G = gtfs.GTFS(dbfname) # handles connections to database etc.
data = G.get_all_route_shapes(use_shapes=shapes)
routes = []
for raw_route in data:
agency = raw_route["agency"]
lats = [float(lat) for lat in raw_route['lats']]
lons = [float(lon) for lon in raw_route['lons']]
route_type = int(raw_route['type'])
name = str(raw_route['name'])
agency_name = str(raw_route['agency_name'])
route = {
"agency": agency,
"lats": lats,
"lons": lons,
"route_type": route_type,
"name": name,
"agency_name": agency_name
}
routes.append(route)
return json.dumps(routes)
@app.route("/spreading")
def view_spreading_explorer():
dbfname = get_dbfname(request.args.get('dbfname', None))
shapes = request.args.get('use_shapes', None)
tstart = request.args.get('tstart', None)
tend = request.args.get('tend', None)
lat = request.args.get('lat', None)
lon = request.args.get('lon', None)
if not dbfname:
return json.dumps({})
if tstart:
tstart = int(tstart)
if tend:
tend = int(tend)
if lat:
lat = float(lat)
if lon:
lon = float(lon)
if shapes == "1":
shapes = True
else:
shapes = False
# handles connections to database etc.
G = gtfs.GTFS(dbfname)
data = G.get_spreading_trips(tstart, lat, lon, tend - tstart, use_shapes=shapes)
# add shapes later: use_shapes=shapes)
return json.dumps(data)
application = app # for deployment via WSGI.
if __name__ == "__main__":
runner = Runner(app)
runner.run()