def on_delete(self, req, resp, type_: str): """ Method executed for DELETE requests. Used to delete 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, "DELETE", type_) if endpoint_['method']: # No Delete Operation for collections if type_ in get_doc(resp).parsed_classes and type_ + "Collection" not in get_doc(resp).collections: try: crud.delete_single(type_, session=get_session(resp)) response = {"message": "Object successfully deleted"} resp.media = response return set_response_headers(resp) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code=status_code)
def items_delete_check_support(id_, class_type, path, is_collection): """Check if class_type supports PUT operation""" try: # Delete the Item with ID == id_ # for colletions, id_ is corresponding to their collection_id and not the id_ # primary key crud.delete(id_, class_type, session=get_session(), collection=is_collection) method = "DELETE" resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}/{id_}" last_job_id = crud.get_last_modification_job_id(session=get_session()) new_job_id = crud.insert_modification_record(method, resource_url, session=get_session()) send_sync_update(socketio=socketio, new_job_id=new_job_id, last_job_id=last_job_id, method=method, resource_url=resource_url) status_description = f"Object with ID {id_} successfully deleted" status = HydraStatus(code=200, title="Object successfully deleted.", desc=status_description) return set_response_headers(jsonify(status.generate())) except (ClassNotFound, InstanceNotFound) as e: error = e.get_HTTP() return error_response(error)
def delete(self, type_: str) -> Response: """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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) endpoint_ = checkEndpoint("DELETE", type_) if endpoint_['method']: # 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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) abort(endpoint_['status'])
def on_delete(self, req, resp, id_: int, type_: str): """Delete object with id=id_ from database.""" 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, "DELETE"): # Check if class_type supports PUT operation try: # Delete the Item with ID == id_ crud.delete(id_, class_type, session=get_session(resp)) response = { "message": "Object with ID %s successfully deleted" % (id_)} resp.media = response return set_response_headers(resp) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code= status_code) resp.status = falcon.HTTP_405
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: 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, "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 delete(self, id_, type_): """Delete object with id=id_ from database.""" 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, "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)
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 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 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, 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 items_post_check_support(id_, object_, class_path, path, is_collection): """Check if class_type supports POST operation""" collections, parsed_classes = get_collections_and_parsed_classes() if path in parsed_classes: class_path = path obj_type = getType(path, "PUT") elif path in collections: collection = collections[path]["collection"] class_path = collection.path obj_type = collection.name link_props, link_type_check = get_link_props(class_path, object_) # Load new object and type if (validate_object(object_, obj_type, class_path) and link_type_check): if is_collection: object_ = parse_collection_members(object_) 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(), collection=is_collection) method = "POST" resource_url = f"{get_hydrus_server_url()}{get_api_name()}/{path}/{object_id}" last_job_id = crud.get_last_modification_job_id( session=get_session()) new_job_id = crud.insert_modification_record(method, resource_url, session=get_session()) send_sync_update(socketio=socketio, new_job_id=new_job_id, last_job_id=last_job_id, method=method, resource_url=resource_url) headers_ = [{"Location": resource_url}] status_description = (f"Object with ID {object_id} successfully " "updated") status = HydraStatus(code=200, title="Object updated", desc=status_description) return set_response_headers(jsonify(status.generate()), headers=headers_) except (ClassNotFound, InstanceNotFound, InstanceExists, PropertyNotFound) as e: error = e.get_HTTP() return error_response(error) else: error = HydraError(code=400, title="Data is not valid") return error_response(error)
def verify_user() -> Union[Response, None]: """ Verify the credentials of the user and assign token. """ try: auth = check_authorization(request, get_session()) if auth is False: return failed_authentication(True) elif get_token(): token = add_token(request, get_session()) return token_response(token) except Exception as e: status_code, message = e.get_HTTP() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) return None
def verify_user() -> Union[Response, None]: """ Verify the credentials of the user and assign token. """ try: auth = check_authorization(request, get_session()) if auth is False: return failed_authentication(True) elif get_token(): token = add_token(request, get_session()) return token_response(token) except Exception as e: error = e.get_HTTP() # type: HydraError return error_response(error) return None
def get(self, type_: str) -> Response: """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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) endpoint_ = checkEndpoint("GET", type_) if endpoint_['method']: # 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() # type: ignore 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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) abort(endpoint_['status'])
def on_get(self, req, resp, type_): """Retrieve a collection of items from the database.""" 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) if checkEndpoint(resp, "GET", type_): # Collections if type_ in get_doc(resp).collections: collection = get_doc(resp).collections[type_]["collection"] try: resp.media = crud.get_collection(get_api_name(resp), collection.class_.title, session=get_session(resp)) return set_response_headers(resp) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code=status_code) # Non Collection classes elif type_ in get_doc( resp ).parsed_classes and type_ + "Collection" not in get_doc( resp).collections: try: resp.media = hydrafy( resp, crud.get_single(type_, api_name=get_api_name(resp), session=get_session(resp))) return set_response_headers(resp) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code=status_code)
def delete(self, path, int_list): """ To delete multiple objects :param path: endpoints :param int_list: Optional String containing ',' separated ID's :return: """ 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, "DELETE"): # Check if class_type supports PUT operation try: # Delete the Item with ID == id_ crud.delete_multiple(int_list, class_type, session=get_session()) response = { "message": "Object with ID %s successfully deleted" % (int_list.split(',')) } return set_response_headers(jsonify(response)) except (ClassNotFound, InstanceNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) abort(405)
def delete(self, path: str) -> Response: """ Method executed for DELETE requests. Used to delete a non-collection class. :param path - Path for Item ( Specified in APIDoc @id) """ auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response endpoint_ = checkEndpoint("DELETE", path) if endpoint_['method']: # No Delete Operation for collections if path in get_doc().parsed_classes and path + \ "Collection" not in get_doc().collections: try: class_type = get_doc().parsed_classes[path]['class'].title crud.delete_single(class_type, session=get_session()) response = {"message": "Object successfully deleted"} return set_response_headers(jsonify(response)) except (ClassNotFound, InstanceNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) abort(endpoint_['status'])
def delete(self, id_: str, path: str) -> Response: """Delete object with id=id_ from database.""" 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, "DELETE"): # Check if class_type supports PUT operation try: # Delete the Item with ID == id_ crud.delete(id_, class_type, session=get_session()) response = { "message": "Object with ID %s successfully deleted" % (id_) } return set_response_headers(jsonify(response)) except (ClassNotFound, InstanceNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) abort(405)
def get(self, id_: str, path: str) -> Response: """ GET object with id = id_ from the database. :param id : Item ID :param path : Path for Item ( 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, "GET"): # Check if class_type supports GET operation try: # Try getting the Item based on ID and Class type response = crud.get(id_, class_type, api_name=get_api_name(), session=get_session()) return set_response_headers( jsonify(hydrafy(response, path=path))) except (ClassNotFound, InstanceNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) abort(405)
def get(self, id_: int, type_: str) -> Response: """ GET object with id = id_ from the database. :param id : Item ID :param type_ : Item type """ 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, "GET"): # Check if class_type supports GET operation try: # Try getting the Item based on ID and Class type 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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) abort(405)
def delete(self, type_: str) -> Response: """ Method executed for DELETE requests. Used to delete a non-collection class. :param type_ - Item type """ auth_response = check_authentication_response() if type(auth_response) == Response: return auth_response endpoint_ = checkEndpoint("DELETE", type_) if endpoint_['method']: # 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() # type: ignore return set_response_headers(jsonify(message), status_code=status_code) abort(endpoint_['status'])
def parse_collection_members(object_: dict) -> dict: """Parse the members of a collection to make it easier to insert in database. :param object_: The body of the request having object members :type object_: dict :return: Object with parsed members :rtype: dict """ members = list() for member in object_['members']: # example member # { # "@id": "/serverapi/LogEntry/aab38f9d-516a-4bb2-ae16-068c0c5345bd", # "@type": "LogEntry" # } member_id = member['@id'].split('/')[-1] member_type = member['@type'] if crud.item_exists(member_type, member_id, get_session()): members.append({ "id_": member_id, "@type": member_type, }) else: error = HydraError(code=400, title="Data is not valid") return error_response(error) object_['members'] = members return object_
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 on_get(self, req, resp, id_, type_): """GET object with id = id_ from the database.""" 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, "GET"): try: resp.media = hydrafy(resp, crud.get(id_, class_type, api_name=get_api_name(resp), session=get_session(resp))) return set_response_headers(resp) except Exception as e: status_code, message = e.get_HTTP() resp.media = message return set_response_headers(resp, status_code= status_code) resp.status = falcon.HTTP_405
def finalize_response(path: str, obj: Dict[str, Any]) -> Dict[str, Any]: """ finalize response objects by removing properties which are not readable and correcting path of nested objects. :param path: Path of the collection or non-collection class. :param obj: object being finalized :return: An object not containing any `readable=False` properties and having proper path of any nested object's url. """ for prop in get_doc().parsed_classes[path]["class"].supportedProperty: # Skip not required properties which are not inserted yet. if not prop.required and prop.title not in obj: continue if prop.read is False: obj.pop(prop.title, None) elif isinstance(prop.prop, HydraLink): hydra_link = prop.prop range_class = hydra_link.range.replace("vocab:", "") nested_path, is_collection = get_nested_class_path(range_class) if is_collection: id = obj[prop.title] obj[prop.title] = "/{}/{}/{}".format(get_api_name(), nested_path, id) else: obj[prop.title] = "/{}/{}".format(get_api_name(), nested_path) elif 'vocab:' in prop.prop: prop_class = prop.prop.replace("vocab:", "") id = obj[prop.title] obj[prop.title] = crud.get(id, prop_class, get_api_name(), get_session()) return obj
def items_put_check_support(id_, class_path, path, is_collection): """Check if class_type supports PUT operation""" object_ = json.loads(request.data.decode('utf-8')) collections, parsed_classes = get_collections_and_parsed_classes() if path in parsed_classes: class_path = path obj_type = getType(path, "PUT") elif path in collections: collection = collections[path]["collection"] class_path = collection.path obj_type = collection.name link_props, link_type_check = get_link_props(class_path, object_) # Load new object and type if (validate_object(object_, obj_type, class_path) and link_type_check): if is_collection: object_ = parse_collection_members(object_) try: # Add the object with given ID object_id = crud.insert(object_=object_, id_=id_, session=get_session(), collection=is_collection) headers_ = [{"Location": f"{get_hydrus_server_url()}" f"{get_api_name()}/{path}/{object_id}"}] status_description = f"Object with ID {object_id} successfully added" status = HydraStatus(code=201, title="Object successfully added.", desc=status_description) return set_response_headers( jsonify(status.generate()), headers=headers_, status_code=status.code) except (ClassNotFound, InstanceExists, PropertyNotFound) as e: error = e.get_HTTP() return error_response(error) else: error = HydraError(code=400, title="Data is not valid") return error_response(error)
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 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 get(self, path: str) -> Response: """ Retrieve a collection of items from the database. """ auth_response = check_authentication_response() if isinstance(auth_response, Response): return auth_response endpoint_ = checkEndpoint("GET", path) if endpoint_['method']: # If endpoint and GET method is supported in the API if path in get_doc().collections: # If collection name in document's collections collection = get_doc().collections[path]["collection"] try: # Get collection details from the database response = crud.get_collection(get_api_name(), collection.class_.title, session=get_session(), path=path) return set_response_headers( jsonify(hydrafy(response, path=path))) except ClassNotFound as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) # If class is supported elif path in get_doc( ).parsed_classes and path + "Collection" not in get_doc( ).collections: try: class_type = get_doc().parsed_classes[path]['class'].title response = crud.get_single(class_type, api_name=get_api_name(), session=get_session(), path=path) return set_response_headers( jsonify(hydrafy(response, path=path))) except (ClassNotFound, InstanceNotFound) as e: status_code, message = e.get_HTTP() return set_response_headers(jsonify(message), status_code=status_code) abort(endpoint_['status'])