-
Notifications
You must be signed in to change notification settings - Fork 6
/
api.py
529 lines (426 loc) · 19.6 KB
/
api.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
'''
api.py
All API calls defined here.
# Tornado API functions template:
class APIHandler(tornado.web.RequestHandler):
def get(self):
#get the Argument that User had passed as name in the get request
userInput=self.get_argument('name')
welcomeString=sayHello(userInput)
#return this as JSON
self.write(json.dumps(welcomeString))
def post(self):
user = self.get_argument("username")
passwd = self.get_argument("password")
time.sleep(10)
self.write("Your username is %s and password is %s" % (user, passwd))
'''
class loadJsonsList(tornado.web.RequestHandler):
def get(self):
# /API/loadJsonsList optional parameter: [?which=locked]
start = time.time()
which = self.get_argument('which',default='')
if which != 'locked':
returnContent = recursiveDropdown(routesFolder,ext='.json')
else:
returnContent = recursiveDropdown(lockFolder,ext='.json')
self.write(returnContent)
end = time.time()
logmessage("loadJsonsList GET call took {} seconds.".format(round(end-start,2)))
logUse('routesList')
class loadJson(tornado.web.RequestHandler):
def post(self):
# /API/loadJson?route=filename&key=key
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'MAPPER'):
self.set_status(400)
self.write("Error: Need Mapper level API Key.")
return
filename = self.get_argument('route',default='')
data = json.loads( self.request.body.decode('UTF-8'), object_pairs_hook=OrderedDict )
logmessage(filename)
saveStatus = saveRoute(filename,data, key=key)
self.write(saveStatus)
end = time.time()
logmessage("loadJson POST call (to save a route) took {} seconds.".format(round(end-start,2)))
logUse('saveRoute','write')
class GPXUpload(tornado.web.RequestHandler):
def post(self):
# /API/GPXUpload
start = time.time()
gpx_string = self.request.files['gpx'][0]['body']
gpxDict = xmltodict.parse(gpx_string, attr_prefix='')
waypointDF1 = pd.DataFrame(gpxDict['gpx']['wpt'])
# waypointDF2 = waypointDF1[waypointDF1.name.str.lower() != 'bus stop'][['name','lat','lon','time']].copy()
waypointDF2 = waypointDF1[['name','lat','lon','time']].copy()
# removing extra bus stop entries
waypointDict = waypointDF2.to_dict(orient='records', into=OrderedDict)
trackDict = [ [ x['lat'], x['lon'] ] for x in gpxDict['gpx']['trk']['trkseg']['trkpt'] ]
returnJson = json.dumps({'waypoint':waypointDict, 'track':trackDict}, ensure_ascii=False)
self.write(returnJson)
end = time.time()
logmessage("GPXUpload POST call took {} seconds.".format(round(end-start,2)))
logUse('gpx','read')
class routeSuggest(tornado.web.RequestHandler):
def get(self):
# /API/routeSuggest?route=filename&fuzzy=fuzzy&key=key
start = time.time()
filename = self.get_argument('route',default='')
if not len(filename):
self.set_status(400)
self.write("Error: Load a valid route.")
return
key = self.get_argument('key',default='')
if not checkAccess(key,'MAPPER'):
self.set_status(400)
self.write("Error: Need Mapper level API Key.")
return
fuzzy = ( self.get_argument('fuzzy',default='n') == 'y' )
# logmessage('routeSuggest:',filename)
status = routeSuggestFunc(filename=filename, fuzzy=fuzzy, suggestManual=True, mapAgain=True, key=key)
self.write(status)
end = time.time()
logmessage("routeSuggest GET call took {} seconds.".format(round(end-start,2)))
logUse('routeSuggest','write')
class routeLock(tornado.web.RequestHandler):
def get(self):
# /API/routeLock?route=filename
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'REVIEW'):
self.set_status(400)
self.write("Error: Need Reviewer level API Key.")
return
filename = self.get_argument('route',default='')
if not len(filename):
self.set_status(400)
self.write("Error: Load a valid route.")
return
logmessage('routeLock:',filename)
status = routeLockFunc(filename,key=key)
self.write(status)
end = time.time()
logmessage("routeLock GET call took {} seconds.".format(round(end-start,2)))
logUse('lockRoute','write')
class bulkSuggest(tornado.web.RequestHandler):
def get(self):
# /API/bulkSuggest?mapFirst=${mapFirst}&suggestManual=${suggestManual}&mapAgain=${mapAgain}&jumpers=${jumpers}&depot=${depot}&key=${globalApiKey}
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'ADMIN'):
self.set_status(400)
self.write("Error: Need Admin level API Key.")
return
mapFirst = ( self.get_argument('mapFirst',default='n') == 'y' )
suggestManual = ( self.get_argument('suggestManual',default='n') == 'y' )
mapAgain = ( self.get_argument('mapAgain',default='n') == 'y' )
fuzzy = ( self.get_argument('fuzzy',default='n') == 'y' )
jumpers = ( self.get_argument('jumpers',default='n') == 'y' )
dryRun = not ( self.get_argument('dryRun',default='y') == 'n' )
depot = self.get_argument('depot',default='')
# skipEmpty = ( self.get_argument('skipEmpty',default='n') == 'y' )
logmessage('Beginning bulkSuggest function. This may take long.')
logmessage('mapFirst:',mapFirst)
logmessage('suggestManual:',suggestManual)
logmessage('mapAgain:',mapAgain)
logmessage('fuzzy:',fuzzy)
logmessage('jumpers:',jumpers)
logmessage('dryRun (for removing jumpers):',dryRun)
logmessage('depot:',depot)
# logmessage('skipEmpty:',skipEmpty)
routesList = getallRoutes() # returns a list like ['CNT/1.json','BDG/2.json'...]
dfMapped=loadMappedStops()
dfDataBank=loadDataBank()
returnMessages = []
for filename in routesList:
if filename.endswith('unmapped.json'): continue # want to skip bulk-mapping for this one.
# 5.5.19 : intervention : depot-restriction
if len(depot) and (not filename.startswith(depot)): continue # if a depot is specified, don't run
status = routeSuggestFunc(filename=filename, dfMapped=dfMapped, dfDataBank=dfDataBank, mapFirst=mapFirst, suggestManual=suggestManual, mapAgain=mapAgain, fuzzy=fuzzy, key=key)
returnMessages.append( status )
if jumpers:
status = sanityFunc(filename,key=key,dryRun=dryRun)
returnMessages.append( status )
logmessage('\n'.join(returnMessages))
self.write('<br>'.join(returnMessages))
end = time.time()
logmessage("bulkSuggest GET call took {} seconds.".format(round(end-start,2)))
logUse('bulkRouteSuggest','bulk')
class keyCheck(tornado.web.RequestHandler):
def get(self):
# /API/keyCheck?key=${globalApiKey}
start = time.time()
key = self.get_argument('key',default='')
returnData = userInfo(key)
if not returnData:
self.set_status(400)
self.write("Error: Invalid API Key.")
return
self.write(json.dumps(returnData))
end = time.time()
logmessage("keyCheck GET call took {} seconds.".format(round(end-start,2)))
class routeEntry(tornado.web.RequestHandler):
def post(self):
# /API/GPXUpload
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'DATAENTRY'):
self.set_status(400)
self.write("Error: Need DATAENTRY level API Key.")
return
route = self.get_argument('route',default='')
if not route:
self.set_status(400)
self.write("Error: Need valid route.")
return
data = json.loads( self.request.body.decode('UTF-8'), object_pairs_hook=OrderedDict )
logmessage('routeEntry save:',route)
returnMessage = saveDataEntryRoute(route,data,key)
self.write(returnMessage)
end = time.time()
logmessage("routeEntry POST call for route {} took {} seconds.".format(route,round(end-start,2)))
logUse('saveRouteDataEntry','write')
class reconcile(tornado.web.RequestHandler):
def post(self):
# /API/reconcile?key=${globalApiKey}
start = time.time()
mode = self.get_argument('mode',default='')
requiredLevel = 'REVIEW' if mode=='unmapped' else 'ADMIN'
key = self.get_argument('key',default='')
if not checkAccess(key,requiredLevel):
self.set_status(400)
self.write("Error: Need {} level API Key.".format(requiredLevel))
return
data = json.loads( self.request.body.decode('UTF-8'), object_pairs_hook=OrderedDict )
# logmessage(json.dumps(data,indent=2)) # to see what the incoming data looks like
returnList = []
recon_stop_name = data.get('recon_stop_name')
recon_stop_desc = data.get('recon_stop_desc')
recon_stop_lat = data.get('recon_stop_lat')
recon_stop_lon = data.get('recon_stop_lon')
for stopDetail in data.get('stops',[]):
folder = stopDetail.get('folder')
jsonFile = stopDetail.get('jsonFile')
direction_id = stopDetail.get('direction_id')
searchName = stopDetail.get('stop_name')
if stopDetail.get('workStatus') == 'working':
status= changeStop(key,folder,jsonFile,direction_id,searchName,recon_stop_name,recon_stop_desc,recon_stop_lat,recon_stop_lon)
else:
status = "{}/{} is locked so no changes there.".format(folder,jsonFile)
returnList.append(status)
self.write('<br>'.join(returnList) )
end = time.time()
logmessage("reconcile POST call took {} seconds.".format(round(end-start,2)))
logUse('reconcile','bulk')
comment = ''' # this is what a standard json object received in this API call looks like:
{
"recon_stop_name": "Basheer Bagh",
"recon_stop_desc": "",
"recon_stop_lat": 17.4018,
"recon_stop_lon": 78.47571,
"stops": [
{
"sr": "247",
"workStatus": "working",
"folder": "KCG",
"jsonFile": "136H.json",
"depot": "KCG",
"routeName": "136H",
"direction_id": "0",
"stop_sequence": "23",
"stop_name": "Basheer Bagh",
"stop_lat": "17.4018",
"stop_lon": "78.47571",
"zap": "basheerbagh",
"confidence": "1",
"stop_desc": ""
},
{
"sr": "255",
"workStatus": "working",
"folder": "KCG",
"jsonFile": "136H.json",
"depot": "KCG",
"routeName": "136H",
"direction_id": "1",
"stop_sequence": "4",
"stop_name": "Basheer Bagh",
"stop_lat": "17.4018",
"stop_lon": "78.47571",
"zap": "basheerbagh",
"confidence": "1",
"stop_desc": ""
}
]
}
'''
class getRouteLine(tornado.web.RequestHandler):
def get(self):
# /API/getRouteLine?folder=folder&jsonFile=jsonFile&direction_id=direction_id
start = time.time()
folder = self.get_argument('folder',default='')
jsonFile = self.get_argument('jsonFile',default='')
direction_id = str(self.get_argument('direction_id',default=''))
if not (folder and jsonFile):
self.set_status(400)
self.write("Error: Need valid route.")
return
returnContent = routeLine(folder,jsonFile,direction_id) # get an array of lat-longs like [[1,2],[1,3]]
self.write(json.dumps(returnContent)) # send it in json format
end = time.time()
logmessage("getRouteLine GET call for {}/{}:{} took {} seconds.".format(folder,jsonFile,direction_id,round(end-start,2)))
logUse('getRouteLine','read')
class removeAutoMappingAPI(tornado.web.RequestHandler):
def get(self):
# /API/removeAutoMappingAPI?really=${removeReally}&deSuggest=${removeSuggestions}&key=${globalApiKey}
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'ADMIN'):
self.set_status(400)
self.write("Error: Need ADMIN level API Key.")
return
really = self.get_argument('really',default='n') == 'y'
deSuggest = self.get_argument('deSuggest',default='n') == 'y'
returnList = removeAutoMapping(key,really,deSuggest)
self.write('<br>'.join(returnList) )
end = time.time()
logmessage("removeAutoMappingAPI GET call took {} seconds.".format(round(end-start,2)))
logUse('removeAutoMapping','bulk')
class timings(tornado.web.RequestHandler):
def post(self):
# /API/timings?key=${globalApiKey}&route=${globalRoute}
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'MAPPER'):
self.set_status(400)
self.write("Error: Need MAPPER level API Key.")
return
route = self.get_argument('route',default='')
if not route:
self.set_status(400)
self.write("Error: Need valid route.")
return
data = json.loads( self.request.body.decode('UTF-8'), object_pairs_hook=OrderedDict )
returnStatus = storeTimings(route,data,key)
logmessage(returnStatus)
self.write(returnStatus)
end = time.time()
logmessage("timings POST call took {} seconds.".format(round(end-start,2)))
logUse('saveRouteTimings','write')
class unLock(tornado.web.RequestHandler):
def get(self):
# /API/unLock?route=${filename}&key=${globalApiKey}
start = time.time()
key = self.get_argument('key',default='')
filename = self.get_argument('route',default='')
if not checkAccess(key,'ADMIN'):
self.set_status(400)
self.write("Error: Need Admin level API Key.")
return
if not len(filename):
self.set_status(400)
self.write("Error: Invalid route.")
return
status = unLockFunc(filename=filename,key=key)
self.write(status)
end = time.time()
logmessage("unLock GET call took {} seconds.".format(round(end-start,2)))
logUse('unLockRoute','write')
class depotsList(tornado.web.RequestHandler):
def get(self):
# /API/depotsList optional parameter: [?which=locked]
start = time.time()
which = self.get_argument('which',default='')
returnContent = depotsListFunc()
self.write(returnContent)
end = time.time()
logmessage("depotsList GET call took {} seconds.".format(round(end-start,2)))
logUse('depotsList')
#################################
# 21.4.19
# from https://stackoverflow.com/a/55762431/4355695 : restrict direct browser access to .py files and stuff
class MyStaticFileHandler(tornado.web.StaticFileHandler):
def validate_absolute_path(self, root, absolute_path):
if any([absolute_path.endswith(x) for x in forbiddenEndings]) or any([ (x in absolute_path) for x in forbiddenPaths]):
# raise tornado.web.HTTPError(403) # this is the usual thing: raise 403 Forbidden error. But instead..
# self.write('YOU SHALL NOT PASS!')
logUse('forbidden','hack')
return os.path.join(root,'lib','errorpage.txt')
if absolute_path.endswith('favicon.ico'):
# gosh darnit this doesn't work on payanam site because the path itself is to server.nikhilvj.co.in
return os.path.join(root,'lib','favicon.ico')
return super().validate_absolute_path(root, absolute_path) # you may pass
###################################
# CODE GRAVEYARD:
'''
discard; load csv on js side using papa.parse
class getDatabank(tornado.web.RequestHandler):
def get(self):
# /API/getDatabank?searchName=${searchName}&fuzzyFlag=${fuzzyFlag}&jellyFlag=${jellyFlag}
start = time.time()
searchName = self.get_argument('searchName',default='')
logmessage(searchName)
fuzzyFlag = self.get_argument('fuzzyFlag',default='n')
jellyFlag = self.get_argument('jellyFlag',default='n')
with open(configFile) as f:
configDict = json.load(f)
databank = configDict.get('databank', 'hydstopsGoogle3.csv')
try:
df = pd.read_csv(databankFolder+databank)
except OSError as e:
logmessage('Error:',e)
self.set_status(400)
self.write('Error:' + str(e))
return
if jellyFlag == 'y':
Jstart = time.time()
df2 = jellyPanda(searchName,df)
Jend = time.time()
logmessage("Jellyfish scoring took {} seconds.".format(round(Jend-Jstart,3)))
else: df2 = df
if fuzzyFlag == 'y':
Fstart = time.time()
df3 = fuzzyPanda(searchName,df2)
Fend = time.time()
logmessage("Fuzywuzzy scoring took {} seconds.".format(round(Fend-Fstart,3)))
else: df3 = df2
rightJson = df3.to_json(orient='records', force_ascii=False)
del df,df2,df3 # cleaning up
self.write(rightJson)
end = time.time()
logmessage("getDatabank GET call took {} seconds.".format(round(end-start,2)))
class catchJumpers(tornado.web.RequestHandler):
def get(self):
# /API/catchJumpers?route=filename&key=${globalApiKey}&dryRun=n
start = time.time()
key = self.get_argument('key',default='')
if not checkAccess(key,'ADMIN'):
self.set_status(400)
self.write("Error: Need Admin level API Key.")
return
route = self.get_argument('route',default='')
if not route:
self.set_status(400)
self.write("Error: Need valid route.")
return
dryRun = not ( self.get_argument('dryRun',default='y') == 'n' )
returnMessage = sanityFunc(route,key,dryRun)
self.write(returnMessage)
end = time.time()
logmessage("catchJumpers GET call for route {} took {} seconds.".format(route,round(end-start,2)))
def get(self):
# /API/loadJson?route=filename
start = time.time()
filename = self.get_argument('route',default='')
logmessage(filename)
if not filename or not os.path.exists(os.path.join(routesFolder,filename)):
self.set_status(400)
self.write("Error: invalid filename.")
return
with open(os.path.join(routesFolder,filename)) as fh:
a = json.load(fh)
self.write(json.dumps(a) )
end = time.time()
logmessage("loadJson GET call took {} seconds.".format(round(end-start,2)))
'''