/
api.py
436 lines (346 loc) · 12.2 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
from lib.search import search
from flask import Blueprint, make_response, request, current_app
import json
import time
import datetime
from datetime import timedelta
from functools import update_wrapper
api = Blueprint('api', __name__, template_folder='templates')
EVENT_SOURCES = ["wesleying", "wesleyanEvents"]
"""
Cross domain
http://flask.pocoo.org/snippets/56/
"""
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
"""
TODO: Refactor some of this to get rid of the
repeated code..
"""
def err_response(errMsg):
"""
Responds with:
{"ERROR":errMsg}
"""
return json.dumps({"ERROR": errMsg})
def validate_max_results_arg(req_max_results, min_results, max_results):
try:
req_max_results = int(req_max_results)
errMsg = "Please specify between " + \
str(min_results) + " and " + str(max_results) + " maxresults."
if req_max_results < min_results:
return [False, err_response(errMsg)]
if req_max_results > 100:
return [False, err_response(errMsg)]
else:
return [True, req_max_results]
except:
errMsg = ("Unable to process your request, please ensure your"
" request is properly formatted.")
return [False, err_response(errMsg)]
def validate_source(req_source, accepted_sources):
return req_source in accepted_sources
def time_from_raw_string(raw_time):
try:
nt = time.strptime(raw_time, "%m-%d-%Y")
new_date = datetime.datetime(
month=nt.tm_mon,
day=nt.tm_mday,
year=nt.tm_year
)
return new_date
except:
return False
def validate_search_request(request_obj, min_results, max_results):
"""
Grabs search terms from request if they exist, including:
-title
-location
-time_from
-time_until
-category_query
-source
-maxresults
"""
raw_title = request.args.get('title')
raw_location = request.args.get('location')
raw_time_from = request.args.get('timeFrom')
raw_time_until = request.args.get('timeUntil')
raw_category = request.args.get('category')
raw_source = request.args.get('source')
raw_max_results = request.args.get('maxresults')
if raw_time_from:
raw_time_from = time_from_raw_string(raw_time_from)
if not raw_time_from:
return [False, err_response("Invalid: time from")]
if raw_time_until:
raw_time_until = time_from_raw_string(raw_time_until)
if not raw_time_until:
return [False, err_response("Invalid: time until")]
if raw_max_results:
# check the request
valid = validate_max_results_arg(
raw_max_results, min_results, max_results)
if not valid[0]:
return [False, valid[1]]
# grab the int-ified result from validate since valid
raw_max_results = valid[1]
else:
raw_max_results = max_results
return [True, {"max_results": raw_max_results, "source": raw_source,
"title": raw_title, "location": raw_location,
"time_from": raw_time_from, "time_until": raw_time_until,
"category": raw_category}]
def validate_request(request_obj, min_results, max_results, accepted_sources=None):
"""
Pulls out maxresults and source out of args.
Validates maxresults and source, if either bad, returns
[False, errormsg], else, [True,maxresults,source].
If no maxresults or source in request, return defaults,
respectively.
Right now, source only allows for one source.
"""
req_max_results = request.args.get('maxresults')
raw_data_source = request.args.get('source')
if req_max_results:
# check the request
valid = validate_max_results_arg(
req_max_results, min_results, max_results)
if not valid[0]:
return [False, valid[1]]
# grab the int-ified result from validate since valid
req_max_results = valid[1]
else:
req_max_results = max_results
if raw_data_source and accepted_sources:
# validate source
valid = validate_source(raw_data_source, accepted_sources)
if not valid:
source_string = ",".join(accepted_sources)
return [False, err_response("Invalid source, please select from: " + source_string)]
data_source = raw_data_source
else:
data_source = None
return [True, {"max_results": req_max_results, "source": data_source}]
def validate_search_results(search_results):
"""
Expects a list of mongo objects
"""
if not search_results:
return json.dumps({"Result Count": 0, "Results": []})
final_objs = format_mongo_objs(search_results)
response = {"Result Count": len(final_objs),
"Results": final_objs}
return json.dumps(response)
def format_mongo_objs(mongo_objs):
"""
Formats python datetime into isoformat for each mongo_obj
if the obj has a time.
Also strips out object ID
"""
if not mongo_objs:
return []
for mongo_obj in mongo_objs:
# remove object_id
try:
mongo_obj.pop('_id')
except:
print "API: mongo_obj has no _id, panic!"
old_time = mongo_obj.get('time')
if old_time:
mongo_obj['time'] = old_time.isoformat()
#Case for times nested in "data" field, for static json
data = mongo_obj.get('data')
if data:
old_time_2 = data.get('time')
if old_time_2:
print mongo_obj['data']['time'][0]
mongo_obj['data']['time'][0] = old_time_2[0].isoformat()
return mongo_objs
def format_status(status):
return dict((i["name"], {"time": i["time"], "status": i["status"]}) for i in status)
"""
GENERAL ROUTES
"""
@api.route('/status', methods=['GET'])
@crossdomain(origin='*')
def get_status():
tmp = format_mongo_objs(search.get_status())
return json.dumps(format_status(tmp))
"""
EVENTS
"""
@api.route('/events/today', methods=['GET'])
@crossdomain(origin='*')
def get_today_events():
return get_events(True)
@api.route('/events/latest', methods=['GET'])
@crossdomain(origin='*')
def get_latest_events():
return get_events()
@api.route('/events/search', methods=['GET'])
@crossdomain(origin='*')
def search_events_route():
return search_events()
def search_events():
"""
Moar powarful searching RAWR!
"""
# default
MIN_RESULTS = 1
MAX_RESULTS = 100
validation_result = validate_search_request(
request, MIN_RESULTS, MAX_RESULTS)
if not validation_result[0]:
return validation_result[1]
else:
req_max_results = validation_result[1]['max_results']
req_source = validation_result[1]['source']
req_title = validation_result[1]['title']
req_time_from = validation_result[1]['time_from']
req_time_until = validation_result[1]['time_until']
req_category = validation_result[1]['category']
req_location = validation_result[1]['location']
# Now search, check, and respond
"""
def search_events(numResults,title_query,location_query,
time_from,time_until,category_query,source):
"""
search_results = search.search_events(
numResults=req_max_results,
title_query=req_title,
location_query=req_location,
time_from=req_time_from,
time_until=req_time_until,
category_query=req_category,
source=req_source)
return validate_search_results(search_results)
def get_events(today=False):
"""
Returns latest results.
Maxresults defaults to 100.
Max is 100
Min is 1
"""
# default
MIN_RESULTS = 1
MAX_RESULTS = 100
accepted_sources = ["Wesleying", "Wesleyan Events"]
validation_result = validate_request(
request, MIN_RESULTS, MAX_RESULTS, accepted_sources)
if not validation_result[0]:
return validation_result[1]
else:
req_max_results = validation_result[1]['max_results']
req_source = validation_result[1]['source']
# Now search, check, and respond
if today:
search_results = search.get_events_today()
else:
search_results = search.get_events(req_max_results, req_source)
return validate_search_results(search_results)
@api.route('/events/sources', methods=['GET'])
@crossdomain(origin='*')
def get_sources():
return json.dumps(EVENT_SOURCES)
"""
MENUS
/all --gets everything
/usdan --only holds the daily menu (future?)
/starandcrescent --holds the weekly menu
/redandblack --static
/weswings --static
/summerfields --static
/latenight --static
"""
@api.route('/menus/all', methods=['GET'])
@crossdomain(origin='*')
def get_menus_all():
sources = {
"summerfields": [], "weswings": [], "redandblack": [],
"latenight": [], "starandcrescent": []}
for i in sources:
sources[i] = format_mongo_objs(search.get_menu_static(i))
sources["usdan"] = format_mongo_objs(search.get_menu_usdan())
return json.dumps({"Results": sources})
@api.route('/menus/usdan', methods=['GET'])
@crossdomain(origin='*')
def get_menus_usdan():
return json.dumps({"Results": format_mongo_objs(search.get_menu_usdan())})
@api.route('/menus/starandcrescent', methods=['GET'])
@crossdomain(origin='*')
def get_menus_starandcrescent():
return json.dumps({"Results": format_mongo_objs(search.get_menu_static("sandc"))})
@api.route('/menus/redandblack', methods=['GET'])
@crossdomain(origin='*')
def get_menus_redandblack():
return json.dumps({"Results": format_mongo_objs(search.get_menu_static("redandblack"))})
@api.route('/menus/weswings', methods=['GET'])
@crossdomain(origin='*')
def get_menus_weswings():
return json.dumps({"Results": format_mongo_objs(search.get_menu_static("weswings"))})
@api.route('/menus/summerfields', methods=['GET'])
@crossdomain(origin='*')
def get_menus_summerfields():
return json.dumps({"Results": format_mongo_objs(search.get_menu_static("summerfields"))})
@api.route('/menus/latenight', methods=['GET'])
@crossdomain(origin='*')
def get_menus_latenight():
return json.dumps({"Results": format_mongo_objs(search.get_menu_static("latenight"))})
"""
FILM SERIES METHODS
"""
def get_film_series(today=False):
if today:
search_results = search.get_film_series_today()
else:
search_results = search.get_film_series_all()
# only need to validate the usdan ones.
return validate_search_results(search_results)
@api.route('/filmseries/all')
@crossdomain(origin='*')
def get_film_series_all():
return get_film_series()
@api.route('/filmseries/today')
@crossdomain(origin='*')
def get_film_series_today():
return get_film_series(True)
"""
DIRECTORY METHODS
"""
@api.route('/directory')
@crossdomain(origin='*')
def get_directory():
return validate_search_results(search.get_directory())