-
Notifications
You must be signed in to change notification settings - Fork 130
/
app.py
443 lines (340 loc) · 18.4 KB
/
app.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
"""Main route for the applciation."""
import json
from flask import Flask, jsonify, request, abort
from flask_restful import Api, Resource
from flask_cors import CORS
from hydrus.data import crud
from hydrus.data.user import check_authorization
from hydrus.utils import get_session, get_doc, get_api_name, get_hydrus_server_url, get_authentication
import pdb
def validObject(object_):
"""Check if the data passed in POST is of valid format or not."""
if "@type" in object_:
return True
return False
def failed_authentication():
"""Return failed authentication object."""
message = {401: "Need credentials to authenticate"}
response = set_response_headers(jsonify(message), status_code=401,
headers=[{'WWW-Authenticate': 'Basic realm="Login Required"'}])
return response
def set_response_headers(resp, ct="application/ld+json", headers=[], status_code=200):
"""Set the response headers."""
resp.status_code = status_code
for header in headers:
resp.headers[list(header.keys())[0]] = header[list(header.keys())[0]]
resp.headers['Content-type'] = ct
resp.headers['Link'] = '<' + get_hydrus_server_url() + \
get_api_name()+'/vocab>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"'
return resp
def hydrafy(object_):
"""Add hydra context to objects."""
object_["@context"] = "/"+get_api_name()+"/contexts/" + object_["@type"] + ".jsonld"
return object_
def checkEndpoint(method, type_):
"""Check if endpoint and method is supported in the API."""
for endpoint in get_doc().entrypoint.entrypoint.supportedProperty:
if type_ == endpoint.name:
for operation in endpoint.supportedOperation:
if operation.method == method:
return True
return False
def getType(class_type, method):
"""Return the @type of object allowed for POST/PUT."""
for supportedOp in get_doc().parsed_classes[class_type]["class"].supportedOperation:
if supportedOp.method == method:
return supportedOp.expects.replace("vocab:", "")
# NOTE: Don't use split, if there are more than one substrings with 'vocab:' not everything will be returned.
def checkClassOp(class_type, method):
"""Check if the Class supports the operation."""
for supportedOp in get_doc().parsed_classes[class_type]["class"].supportedOperation:
if supportedOp.method == method:
return True
return False
class Index(Resource):
"""Class for the EntryPoint."""
def get(self):
"""Return main entrypoint for the api."""
return set_response_headers(jsonify(get_doc().entrypoint.get()))
class Vocab(Resource):
"""Vocabulary for Hydra."""
def get(self):
"""Return the main hydra vocab."""
return set_response_headers(jsonify(get_doc().generate()))
class Entrypoint(Resource):
"""Hydra EntryPoint."""
def get(self):
"""Return application main Entrypoint."""
response = {"@context": get_doc().entrypoint.context.generate()}
return set_response_headers(jsonify(response))
class Item(Resource):
"""Handles all operations(GET, POST, PATCH, DELETE) on Items (item can be anything depending upon the vocabulary)."""
def get(self, id_, type_):
"""GET object with id = id_ from the database."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
class_type = get_doc().collections[type_]["collection"].class_.title
if checkClassOp(class_type, "GET"):
try:
response = crud.get(id_, class_type, api_name=get_api_name(), session=get_session())
return set_response_headers(jsonify(hydrafy(response)))
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
abort(405)
def post(self, id_, type_):
"""Update object of type<type_> at ID<id_> with new object_ using HTTP POST."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
class_type = get_doc().collections[type_]["collection"].class_.title
if checkClassOp(class_type, "POST"):
object_ = json.loads(request.data.decode('utf-8'))
obj_type = getType(class_type, "POST")
if validObject(object_):
if object_["@type"] == obj_type:
try:
object_id = crud.update(object_=object_, id_=id_, type_=object_["@type"], session=get_session(), api_name=get_api_name())
headers_ = [{"Location": get_hydrus_server_url()+get_api_name()+"/"+type_+"/"+str(object_id)}]
response = {"message": "Object with ID %s successfully updated" % (object_id)}
return set_response_headers(jsonify(response), headers=headers_)
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400)
abort(405)
def put(self, id_, type_):
"""Add new object_ optional <id_> parameter using HTTP PUT."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
class_type = get_doc().collections[type_]["collection"].class_.title
if checkClassOp(class_type, "PUT"):
object_ = json.loads(request.data.decode('utf-8'))
obj_type = getType(class_type, "PUT")
if validObject(object_):
if object_["@type"] == obj_type:
try:
object_id = crud.insert(object_=object_, id_=id_, session=get_session())
headers_ = [{"Location": get_hydrus_server_url()+get_api_name()+"/"+type_+"/"+str(object_id)}]
response = {"message": "Object with ID %s successfully added" % (object_id)}
return set_response_headers(jsonify(response), headers=headers_, status_code=201)
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400)
abort(405)
def delete(self, id_, type_):
"""Delete object with id=id_ from database."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
class_type = get_doc().collections[type_]["collection"].class_.title
if checkClassOp(class_type, "DELETE"):
try:
crud.delete(id_, class_type, session=get_session())
response = {"message": "Object with ID %s successfully deleted" % (id_)}
return set_response_headers(jsonify(response))
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
abort(405)
class ItemCollection(Resource):
"""Handle operation related to ItemCollection (a collection of items)."""
def get(self, type_):
"""Retrieve a collection of items from the database."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
if checkEndpoint("GET", type_):
# Collections
if type_ in get_doc().collections:
collection = get_doc().collections[type_]["collection"]
try:
response = crud.get_collection(get_api_name(), collection.class_.title, session=get_session())
return set_response_headers(jsonify(hydrafy(response)))
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
# Non Collection classes
elif type_ in get_doc().parsed_classes and type_+"Collection" not in get_doc().collections:
try:
response = crud.get_single(type_, api_name=get_api_name(), session=get_session())
return set_response_headers(jsonify(hydrafy(response)))
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
abort(405)
def put(self, type_):
"""Add item to ItemCollection."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
if checkEndpoint("PUT", type_):
object_ = json.loads(request.data.decode('utf-8'))
# Collections
if type_ in get_doc().collections:
collection = get_doc().collections[type_]["collection"]
obj_type = collection.class_.title
if validObject(object_):
if object_["@type"] == obj_type:
try:
object_id = crud.insert(object_=object_, session=get_session())
headers_ = [{"Location": get_hydrus_server_url()+get_api_name()+"/"+type_+"/"+str(object_id)}]
response = {"message": "Object with ID %s successfully deleted" % (object_id)}
return set_response_headers(jsonify(response), headers=headers_, status_code=201)
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400)
# Non Collection classes
elif type_ in get_doc().parsed_classes and type_+"Collection" not in get_doc().collections:
obj_type = getType(type_, "PUT")
if object_["@type"] == obj_type:
if validObject(object_):
try:
object_id = crud.insert(object_=object_, session=get_session())
headers_ = [{"Location": get_hydrus_server_url()+get_api_name()+"/"+type_+"/"}]
response = {"message": "Object successfully added"}
return set_response_headers(jsonify(response), headers=headers_, status_code=201)
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400)
abort(405)
def post(self, type_):
"""Update Non Collection class item."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
if checkEndpoint("POST", type_):
object_ = json.loads(request.data.decode('utf-8'))
if type_ in get_doc().parsed_classes and type_+"Collection" not in get_doc().collections:
obj_type = getType(type_, "POST")
if validObject(object_):
if object_["@type"] == obj_type:
# try:
crud.update_single(object_=object_, session=get_session(), api_name=get_api_name())
headers_ = [{"Location": get_hydrus_server_url()+get_api_name()+"/"+type_+"/"}]
response = {"message": "Object successfully updated"}
return set_response_headers(jsonify(response), headers=headers_)
# except Exception as e:
# status_code, message = e.get_HTTP()
# return set_response_headers(jsonify(message), status_code=status_code)
return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400)
abort(405)
def delete(self, type_):
"""Delete a non Collection class item."""
if get_authentication():
if request.authorization is None:
return failed_authentication()
else:
try:
auth = check_authorization(request, get_session())
if auth is False:
return failed_authentication()
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
if checkEndpoint("DELETE", type_):
# No Delete Operation for collections
if type_ in get_doc().parsed_classes and type_+"Collection" not in get_doc().collections:
try:
crud.delete_single(type_, session=get_session())
response = {"message": "Object successfully deleted"}
return set_response_headers(jsonify(response))
except Exception as e:
status_code, message = e.get_HTTP()
return set_response_headers(jsonify(message), status_code=status_code)
abort(405)
class Contexts(Resource):
"""Dynamically genereated contexts."""
def get(self, category):
"""Return the context for the specified class."""
if "Collection" in category:
if category in get_doc().collections:
response = {"@context": get_doc().collections[category]["context"].generate()}
return set_response_headers(jsonify(response))
else:
response = {404: "NOT FOUND"}
return set_response_headers(jsonify(response), status_code=404)
else:
if category in get_doc().parsed_classes:
response = {"@context": get_doc().parsed_classes[category]["context"].generate()}
return set_response_headers(jsonify(response))
else:
response = {404: "NOT FOUND"}
return set_response_headers(jsonify(response), status_code=404)
def app_factory(API_NAME="api"):
"""Create an app object."""
app = Flask(__name__)
CORS(app)
app.url_map.strict_slashes = False
api = Api(app)
api.add_resource(Index, "/"+API_NAME+"/", endpoint="api")
api.add_resource(Vocab, "/"+API_NAME+"/vocab", endpoint="vocab")
api.add_resource(Contexts, "/"+API_NAME+"/contexts/<string:category>.jsonld", endpoint="contexts")
api.add_resource(Entrypoint, "/"+API_NAME+"/contexts/EntryPoint.jsonld", endpoint="main_entrypoint")
api.add_resource(ItemCollection, "/"+API_NAME+"/<string:type_>", endpoint="item_collection")
api.add_resource(Item, "/"+API_NAME+"/<string:type_>/<int:id_>", endpoint="item")
return app
if __name__ == "__main__":
app = app_factory("api")
app.run(host='127.0.0.1', debug=True, port=8080)