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 set_response_headers(resp: falcon.Response, ct: str="application/ld+json", headers: Dict[str, Any]={}, status_code = falcon.HTTP_200) -> falcon.Response: resp.status = status_code resp.set_headers(headers) resp.set_header('Content-type', ct) resp.set_header('Link' ,'<' + get_hydrus_server_url(resp) + \ get_api_name(resp)+'/vocab>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"') return resp
def put(self, id_: str, path: str) -> Response: """Add new object_ optional <id_> parameter using HTTP PUT. :param id_ - ID of Item to be updated :param path - Path for Item type( Specified in APIDoc @id) to be updated """ id_ = str(id_) auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response class_type = get_doc().collections[path]["collection"].class_.title if checkClassOp(class_type, "PUT"): # Check if class_type supports PUT operation object_ = json.loads(request.data.decode('utf-8')) obj_type = getType(class_type, "PUT") # Load new object and type if validObject(object_) and object_["@type"] == obj_type: try: # Add the object with given ID object_id = crud.insert(object_=object_, id_=id_, session=get_session()) headers_ = [{"Location": "{}{}/{}/{}".format( get_hydrus_server_url(), get_api_name(), path, object_id)}] response = { "message": "Object with ID {} successfully added".format(object_id)} return set_response_headers( jsonify(response), headers=headers_, status_code=201) except (ClassNotFound, InstanceExists, PropertyNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) else: return set_response_headers(jsonify({400: "Data is not valid"}), status_code=400) else: 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 put(self, path, int_list="") -> Response: """ To insert multiple objects into the database :param path: endpoint :param int_list: Optional String containing ',' separated ID's :return: """ auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response endpoint_ = checkEndpoint("PUT", path) if endpoint_['method']: # If endpoint and PUT method is supported in the API object_ = json.loads(request.data.decode('utf-8')) object_ = object_["data"] if path in get_doc().collections: # If collection name in document's collections collection = get_doc().collections[path]["collection"] # title of HydraClass object corresponding to collection obj_type = collection.class_.title if validObjectList(object_): type_result = type_match(object_, obj_type) # If Item in request's JSON is a valid object # ie. @type is one of the keys in object_ if type_result: # If the right Item type is being added to the # collection try: # Insert object and return location in Header object_id = crud.insert_multiple( objects_=object_, session=get_session(), id_=int_list) headers_ = [{ "Location": "{}/{}/{}".format(get_hydrus_server_url(), get_api_name(), path, object_id) }] response = { "message": "Object with ID {} successfully added".format( object_id) } return set_response_headers(jsonify(response), headers=headers_, status_code=201) except (ClassNotFound, InstanceExists, PropertyNotFound) 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(endpoint_['status'])
def on_put(self, req, resp, id_: int, type_: str): """Add new object_ optional <id_> parameter using HTTP PUT. :param id_ - ID of Item to be updated :param type_ - Type(Class name) of Item to be updated """ if get_authentication(resp): if req.auth is None: return failed_authentication(resp) else: try: auth = check_authorization(req, get_session(resp)) if auth is False: return failed_authentication(resp) except Exception as e: status_code, message = e.get_HTTP() # type: ignore resp.media = message return set_response_headers(resp, status_code=status_code) class_type = get_doc( resp).collections[type_]["collection"].class_.title if checkClassOp(resp, class_type, "PUT"): # Check if class_type supports PUT operation object_ = req.media obj_type = getType(resp, class_type, "PUT") # Load new object and type if validObject(object_): if object_["@type"] == obj_type: try: # Add the object with given ID object_id = crud.insert(object_=object_, id_=id_, session=get_session(resp)) headers_ = [{ "Location": get_hydrus_server_url(resp) + get_api_name(resp) + "/" + type_ + "/" + str(object_id) }] response = { "message": "Object with ID %s successfully added" % (object_id) } resp.media = response return set_response_headers( resp, headers=headers_[0], status_code=falcon.HTTP_201) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code=status_code) return set_response_headers(resp, status_code=falcon.HTTP_400) resp.status = falcon.HTTP_405
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 post(self, id_: int, type_: str) -> Response: """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() # type: ignore 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() # type: ignore 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 on_post(self, req, resp, type_: str): """ Method executed for POST requests. Used to update a non-collection class. :param type_ - Item type """ if get_authentication(resp): if req.auth is None: return failed_authentication(resp) else: try: auth = check_authorization(req, get_session(resp)) if auth is False: return failed_authentication(resp) except Exception as e: status_code, message = e.get_HTTP() # type: ignore resp.media = message return set_response_headers(resp, status_code=status_code) endpoint_ = checkEndpoint(resp, "POST", type_) if endpoint_['method']: object_ = req.media if type_ in get_doc( resp ).parsed_classes and type_ + "Collection" not in get_doc( resp).collections: obj_type = getType(resp, type_, "POST") if validObject(object_): if object_["@type"] == obj_type: try: crud.update_single(object_=object_, session=get_session(resp), api_name=get_api_name(resp)) headers_ = [{ "Location": get_hydrus_server_url(resp) + get_api_name(resp) + "/" + type_ + "/" }] response = { "message": "Object successfully updated" } resp.media = response return set_response_headers(resp, headers=headers_[0]) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers( resp, status_code=status_code) return set_response_headers(resp, status_code=falcon.HTTP_400)
def set_response_headers(resp: Response, ct: str = "application/ld+json", headers: List[Dict[str, Any]] = [], status_code: int = 200) -> Response: """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 link = "http://www.w3.org/ns/hydra/core#apiDocumentation" resp.headers['Link'] = '<{}{}/vocab>; rel="{}"'.format( get_hydrus_server_url(), get_api_name(), link) return resp
def post(self, id_: str, path: str) -> Response: """Update object of type<path> at ID<id_> with new object_ using HTTP POST. :param id_ - ID of Item to be updated :param path - Path for Item type( Specified in APIDoc @id) """ id_ = str(id_) auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response class_type = get_doc().collections[path]["collection"].class_.title if checkClassOp(class_type, "POST"): # Check if class_type supports POST operation object_ = json.loads(request.data.decode('utf-8')) obj_type = getType(class_type, "POST") # Load new object and type if validObject(object_): if object_["@type"] == obj_type: try: # Update the right ID if the object is valid and matches # type of Item 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() + "/" + path + "/" + str(object_id) }] response = { "message": "Object with ID %s successfully updated" % (object_id) } return set_response_headers(jsonify(response), headers=headers_) except (ClassNotFound, InstanceNotFound, InstanceExists, PropertyNotFound) 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, id_: int, type_: str) -> Response: """Update object of type<type_> at ID<id_> with new object_ using HTTP POST. :param id_ - ID of Item to be updated :param type_ - Type(Class name) of Item to be updated """ auth_response = check_authentication_response() if type(auth_response) == Response: return auth_response class_type = get_doc().collections[type_]["collection"].class_.title if checkClassOp(class_type, "POST"): # Check if class_type supports POST operation object_ = json.loads(request.data.decode('utf-8')) obj_type = getType(class_type, "POST") # Load new object and type if validObject(object_): if object_["@type"] == obj_type: try: # Update the right ID if the object is valid and matches # type of Item 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() # type: ignore 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_: int, type_: str) -> Response: """Add new object_ optional <id_> parameter using HTTP PUT. :param id_ - ID of Item to be updated :param type_ - Type(Class name) of Item to be updated """ auth_response = check_authentication_response() if type(auth_response) == Response: return auth_response class_type = get_doc().collections[type_]["collection"].class_.title if checkClassOp(class_type, "PUT"): # Check if class_type supports PUT operation object_ = json.loads(request.data.decode('utf-8')) obj_type = getType(class_type, "PUT") # Load new object and type if validObject(object_): if object_["@type"] == obj_type: try: # Add the object with given ID 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 (ClassNotFound, InstanceExists, PropertyNotFound) 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: auth = check_authorization(request, get_session()) if auth is False: return failed_authentication() 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 post(self, path: str) -> Response: """ Method executed for POST requests. Used to update a non-collection class. :param path - Path for Item type ( Specified in APIDoc @id) """ auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response endpoint_ = checkEndpoint("POST", path) if endpoint_['method']: object_ = json.loads(request.data.decode('utf-8')) if path in get_doc().parsed_classes and "{}Collection".format(path) not in get_doc( ).collections: obj_type = getType(path, "POST") if check_read_only_props(obj_type, object_): if object_["@type"] == obj_type and check_required_props( obj_type, object_) and validObject(object_): try: crud.update_single( object_=object_, session=get_session(), api_name=get_api_name(), path=path) headers_ = [ {"Location": "{}/{}/".format( get_hydrus_server_url(), get_api_name(), path)}] response = { "message": "Object successfully updated"} return set_response_headers( jsonify(response), headers=headers_) except (ClassNotFound, InstanceNotFound, InstanceExists, PropertyNotFound) 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) else: abort(405) abort(endpoint_['status'])
def post(self, type_: str) -> Response: """ Method executed for POST requests. Used to update a non-collection class. :param type_ - Item type """ auth_response = check_authentication_response() if type(auth_response) == Response: return auth_response endpoint_ = checkEndpoint("POST", type_) if endpoint_['method']: 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 (ClassNotFound, InstanceNotFound, InstanceExists, PropertyNotFound) 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(endpoint_['status'])
def put(self, path: str) -> Response: """ Method executed for PUT requests. Used to add an item to a collection :param path - Path for Item type ( Specified in APIDoc @id) """ auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response endpoint_ = checkEndpoint("PUT", path) if endpoint_['method']: # If endpoint and PUT method is supported in the API object_ = json.loads(request.data.decode('utf-8')) if path in get_doc().collections: # If collection name in document's collections collection = get_doc().collections[path]["collection"] # title of HydraClass object corresponding to collection obj_type = collection.class_.title if validObject(object_): # If Item in request's JSON is a valid object # ie. @type is one of the keys in object_ if object_["@type"] == obj_type: # If the right Item type is being added to the # collection try: # Insert object and return location in Header object_id = crud.insert(object_=object_, session=get_session()) headers_ = [{ "Location": get_hydrus_server_url() + get_api_name() + "/" + path + "/" + 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 (ClassNotFound, InstanceExists, PropertyNotFound) 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) elif path in get_doc( ).parsed_classes and path + "Collection" not in get_doc( ).collections: # If path is in parsed_classes but is not a collection obj_type = getType(path, "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() + "/" + path + "/" }] response = {"message": "Object successfully added"} return set_response_headers(jsonify(response), headers=headers_, status_code=201) except (ClassNotFound, InstanceExists, PropertyNotFound) 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(endpoint_['status'])
def on_put(self, req, resp, type_: str): """ Method executed for PUT requests. Used to add an item to a collection :param type_ - Item type """ if get_authentication(resp): if req.auth is None: return failed_authentication(resp) else: try: auth = check_authorization(req, get_session(resp)) if auth is False: return failed_authentication(resp) except Exception as e: status_code, message = e.get_HTTP() # type: ignore resp.media = message return set_response_headers(resp, status_code=status_code) endpoint_ = checkEndpoint(resp, "PUT", type_) if endpoint_['method']: # If endpoint and PUT method is supported in the API object_ = req.media if type_ in get_doc(resp).collections: # If collection name in document's collections collection = get_doc(resp).collections[type_]["collection"] # title of HydraClass object corresponding to collection obj_type = collection.class_.title if validObject(object_): # If Item in request's JSON is a valid object # ie. @type is one of the keys in object_ if object_["@type"] == obj_type: # If the right Item type is being added to the collection try: # Insert object and return location in Header object_id = crud.insert(object_=object_, session=get_session(resp)) headers_ = [{ "Location": get_hydrus_server_url(resp) + get_api_name(resp) + "/" + type_ + "/" + str(object_id) }] response = { "message": "Object with ID %s successfully added" % (object_id) } resp.media = response return set_response_headers( resp, headers=headers_[0], status_code=falcon.HTTP_201) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers( resp, status_code=status_code) return set_response_headers(resp, status_code=falcon.HTTP_400) elif type_ in get_doc( resp ).parsed_classes and type_ + "Collection" not in get_doc( resp).collections: # If type_ is in parsed_classes but is not a collection obj_type = getType(resp, type_, "PUT") if object_["@type"] == obj_type: if validObject(object_): try: object_id = crud.insert(object_=object_, session=get_session(resp)) headers_ = [{ "Location": get_hydrus_server_url(resp) + get_api_name(resp) + "/" + type_ + "/" }] response = {"message": "Object successfully added"} resp.media = response return set_response_headers( resp, headers=headers_[0], status_code=falcon.HTTP_201) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers( resp, status_code=status_code) return set_response_headers(resp, status_code=falcon.HTTP_400)