def on_post(self, req, resp, revision_id, tag=None):
"""Creates a revision tag."""
body = req.stream.read(req.content_length or 0)
try:
tag_data = yaml.safe_load(body)
except yaml.YAMLError as e:
error_msg = ("Could not parse the request body into YAML data. "
"Details: %s." % e)
LOG.error(error_msg)
raise falcon.HTTPBadRequest(description=e)
try:
resp_tag = db_api.revision_tag_create(revision_id, tag, tag_data)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
except errors.RevisionTagBadFormat as e:
raise falcon.HTTPBadRequest(description=e.format_message())
resp_body = revision_tag_view.ViewBuilder().show(resp_tag)
resp.status = falcon.HTTP_201
resp.body = resp_body
python类HTTPNotFound()的实例源码
def _show_validation_entry(self, req, resp, revision_id, validation_name,
entry_id):
try:
entry_id = int(entry_id)
except ValueError:
raise falcon.HTTPBadRequest(
description='The {entry_id} parameter must be an integer.')
try:
entry = db_api.validation_get_entry(
revision_id, validation_name, entry_id)
except (errors.RevisionNotFound, errors.ValidationNotFound) as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp_body = self.view_builder.show_entry(entry)
return resp_body
def on_delete(self, req, resp, dataset_id, **kwargs):
"""Delete a dataset from the service
This method will delete the entry from the datbase and will also
delete the entire datasets generated by them on filesystem.
:param integer dataset_id: Unique ID of dataset
:returns: Nothing if operation was successful
:rtype: 204 NO CONTENT
"""
try:
delete_task = async_tasks.delete_dataset_by_id(dataset_id)
except LookupError:
raise falcon.HTTPNotFound(description="Couldn't locate dataset")
except OSError as err:
raise falcon.HTTPInternalServerError(description=str(err))
else:
resp.status = falcon.HTTP_204
def on_get(self, req, resp):
"""Return all datasets available on the service
:query boolean use_cache: False if cache must be reloaded, True if
values returned can be those cached.
:returns: A list with all datasets
"""
cache = req.get_param_as_bool("use_cache", blank_as_true=True)
dao = data_access.DatasetDAO()
listdts, err = dao.get_all_datasets(use_cache=cache)
if listdts is None:
raise falcon.HTTPNotFound(description=str(err))
response = [{"dataset": dtst.to_dict()} for dtst in listdts]
resp.body = json.dumps(response)
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200
def guarded_session():
'''
Context manager that will automatically close session on exceptions
'''
try:
session = Session()
yield session
except IrisValidationException as e:
session.close()
raise HTTPBadRequest('Validation error', str(e))
except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
session.close()
raise
except Exception:
session.close()
logger.exception('SERVER ERROR')
raise
def _second_hook(req, resp, resource, params):
headers = req.headers
methods = headers.get('URL-METHODS', '').split(',')
if req.method not in methods:
raise falcon.HTTPNotFound()
def get_object(self, req, resp, path_params, for_update=False):
try:
obj = self.objects_class.get(*path_params, using=self.connection)
except NotFoundError:
raise HTTPNotFound()
return obj
def get_object(self, req, resp, path_params, for_update=False, db_session=None):
"""
:param req: Falcon request
:type req: falcon.request.Request
:param resp: Falcon response
:type resp: falcon.response.Response
:param path_params: path params extracted from URL path
:type path_params: dict
:param for_update: if the object is going to be updated or deleted
:type for_update: bool
:param db_session: SQLAlchemy session
:type db_session: sqlalchemy.orm.session.Session
"""
query = db_session.query(self.objects_class)
if for_update:
query = query.with_for_update()
for key, value in path_params.items():
attr = getattr(self.objects_class, key, None)
query = query.filter(attr == value)
conditions = dict(req.params)
if self.PARAM_RELATIONS in conditions:
conditions.pop(self.PARAM_RELATIONS)
query = self.filter_by(query, conditions)
try:
obj = query.one()
except NoResultFound:
raise HTTPNotFound()
except MultipleResultsFound:
raise HTTPBadRequest('Multiple results', 'Query params match multiple records')
return obj
def get_object(self, req, resp, path_params, for_update=False):
pk = req.context['doc'].get('pk')
if not pk:
raise HTTPNotFound()
obj = self.objects_class.get(pk)
if obj is None:
raise HTTPNotFound()
return obj
def _show_tag(self, req, resp, revision_id, tag):
"""Retrieve details for a specified tag."""
try:
resp_tag = db_api.revision_tag_get(revision_id, tag)
except (errors.RevisionNotFound,
errors.RevisionTagNotFound) as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp_body = revision_tag_view.ViewBuilder().show(resp_tag)
resp.status = falcon.HTTP_200
resp.body = resp_body
def _list_all_tags(self, req, resp, revision_id):
"""List all tags for a revision."""
try:
resp_tags = db_api.revision_tag_get_all(revision_id)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(e.format_message())
resp_body = revision_tag_view.ViewBuilder().list(resp_tags)
resp.status = falcon.HTTP_200
resp.body = resp_body
def _delete_tag(self, req, resp, revision_id, tag):
"""Delete a specified tag."""
try:
db_api.revision_tag_delete(revision_id, tag)
except (errors.RevisionNotFound,
errors.RevisionTagNotFound) as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp.status = falcon.HTTP_204
def _delete_all_tags(self, req, resp, revision_id):
"""Delete all tags for a revision."""
try:
db_api.revision_tag_delete_all(revision_id)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp.status = falcon.HTTP_204
def _show_revision(self, req, resp, revision_id):
"""Returns detailed description of a particular revision.
The status of each ValidationPolicy belonging to the revision is also
included.
"""
try:
revision = db_api.revision_get(revision_id)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
revision_resp = self.view_builder.show(revision)
resp.status = falcon.HTTP_200
resp.body = revision_resp
def on_post(self, req, resp, revision_id, validation_name):
validation_data = req.stream.read(req.content_length or 0)
try:
validation_data = yaml.safe_load(validation_data)
except yaml.YAMLError as e:
error_msg = ("Could not parse the validation into YAML data. "
"Details: %s." % e)
LOG.error(error_msg)
raise falcon.HTTPBadRequest(description=six.text_type(e))
if not validation_data:
error_msg = 'Validation payload must be provided.'
LOG.error(error_msg)
raise falcon.HTTPBadRequest(description=error_msg)
if not all([validation_data.get(x) for x in ('status', 'validator')]):
error_msg = 'Validation payload must contain keys: %s.' % (
', '.join(['"status"', '"validator"']))
LOG.error(error_msg)
raise falcon.HTTPBadRequest(description=error_msg)
try:
resp_body = db_api.validation_create(
revision_id, validation_name, validation_data)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp.status = falcon.HTTP_201
resp.append_header('Content-Type', 'application/x-yaml')
resp.body = self.view_builder.show(resp_body)
def _list_validation_entries(self, req, resp, revision_id,
validation_name):
try:
entries = db_api.validation_get_all_entries(revision_id,
validation_name)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp_body = self.view_builder.list_entries(entries)
return resp_body
def _list_all_validations(self, req, resp, revision_id):
try:
validations = db_api.validation_get_all(revision_id)
except errors.RevisionNotFound as e:
raise falcon.HTTPNotFound(description=e.format_message())
resp_body = self.view_builder.list(validations)
return resp_body
def on_get(self, req, resp, sanitized_params, revision_id):
"""Returns all documents for a `revision_id`.
Returns a multi-document YAML response containing all the documents
matching the filters specified via query string parameters. Returned
documents will be as originally posted with no substitutions or
layering applied.
"""
include_encrypted = policy.conditional_authorize(
'deckhand:list_encrypted_documents', req.context, do_raise=False)
order_by = sort_by = None
if 'order' in sanitized_params:
order_by = sanitized_params.pop('order')
if 'sort' in sanitized_params:
sort_by = sanitized_params.pop('sort')
filters = sanitized_params.copy()
filters['metadata.storagePolicy'] = ['cleartext']
if include_encrypted:
filters['metadata.storagePolicy'].append('encrypted')
filters['deleted'] = False # Never return deleted documents to user.
try:
documents = db_api.revision_get_documents(
revision_id, **filters)
except errors.RevisionNotFound as e:
LOG.exception(six.text_type(e))
raise falcon.HTTPNotFound(description=e.format_message())
sorted_documents = utils.multisort(documents, sort_by, order_by)
resp.status = falcon.HTTP_200
resp.body = self.view_builder.list(sorted_documents)
def _retrieve_documents_for_rendering(self, revision_id, **filters):
try:
documents = db_api.revision_get_documents(
revision_id, **filters)
except errors.RevisionNotFound as e:
LOG.exception(six.text_type(e))
raise falcon.HTTPNotFound(description=e.format_message())
else:
return documents
def on_get(self, req, resp):
raise falcon.HTTPNotFound()
def on_get(self, req, resp):
raise falcon.HTTPNotFound(description='Not Found')
def on_get(self, req, resp, **kwargs):
# simulate that the endpoint is hit but raise a 404 because
# the object isn't found in the database
raise falcon.HTTPNotFound()
def on_get(self, request, response, vertex_id):
try:
results = self.parent.graph.query_vertices({ "id" : vertex_id })
response.body = json.dumps(list(results)[0])
response.status = falcon.HTTP_200
except:
raise falcon.HTTPNotFound()
def on_get(self, request, response):
query = dict()
request.get_param_as_int('transaction', store=query)
if "transaction" in query:
task = self.client.get_task(query['transaction'])
if task is None:
raise falcon.HTTPNotFound()
else:
response.body = task
response.status = falcon.HTTP_200
else:
response.body = json.dumps({}, encoding='utf-8')
response.status = falcon.HTTP_200
def on_delete(self, req, resp, job_id=None):
job = self.eventloop.job_by_id(job_id)
if not job:
raise falcon.HTTPNotFound()
job.set_status(eva.job.DELETED)
self.set_response_message(resp, "The job '%s' has been marked for deletion.")
def on_get(self, req, resp, filename):
suffix = os.path.splitext(req.path)[1]
resp.content_type = mimes.get(suffix, 'application/octet-stream')
filepath = os.path.join(ui_root, self.path, secure_filename(filename))
try:
resp.stream = open(filepath, 'rb')
resp.stream_len = os.path.getsize(filepath)
except IOError:
raise HTTPNotFound()
def on_post(self, req, resp, dataset_id, dataset_dto, entities_pair):
"""This method return the true distance between two entities
{"distance":
["http://www.wikidata.org/entity/Q1492",
"http://www.wikidata.org/entity/Q2807"]
}
:param int dataset_id: The dataset identifier on database
:param DTO dataset_dto: The Dataset DTO from dataset_id (from hook)
:param tuple entities_pair: A pair of entities (from hook)
:returns: A distance attribute, float number
:rtype: dict
"""
dataset_dao = data_access.DatasetDAO()
dataset = dataset_dao.build_dataset_object(dataset_dto) # TODO: design
# Get server to do 'queries'
search_index, err = dataset_dao.get_search_index(dataset_dto)
if search_index is None:
msg_title = "Dataset not ready perform search operation"
raise falcon.HTTPConflict(title=msg_title, description=str(err))
# TODO: Maybe extract server management anywhere to simplify this
search_server = server.Server(search_index)
entity_x, entity_y = entities_pair
id_x = dataset.get_entity_id(entity_x)
id_y = dataset.get_entity_id(entity_y)
if id_x is None or id_y is None:
raise falcon.HTTPNotFound(
description=("The {} id from entity {} or the {} id from {} "
"entity can't be found on the dataset")
.format(id_x, entity_x, id_y, entity_y))
dist = search_server.distance_between_entities(id_x, id_y)
resp.body = json.dumps({"distance": dist})
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200
def on_post(self, req, resp, dataset_id, dataset_dto, entities):
"""Get the embedding given an entity or a list of entities (URI)
{"entities": ["Q1492", "Q2807", "Q1"]}
:param integer dataset_id: Unique ID of dataset
:param integer dataset_dto: Dataset DTO (from hook)
:param list entities: List of entities to get embeddings (from hook)
:returns: A list of list with entities and its embeddings
:rtype: list
"""
istrained = dataset_dto.is_trained()
if istrained is None or not istrained:
raise falcon.HTTPConflict(
title="Dataset has not a valid state",
description="Dataset {} has a {} state".format(
dataset_id, dataset_dto.status))
try:
result = async_tasks.find_embeddings_on_model(dataset_id, entities)
except OSError as err:
filerr = err.filename
raise falcon.HTTPNotFound(
title="The file on database couldn't be located",
description=("A file ({}) has been found on database, but it "
"does not exist on filesystem").format(filerr))
textbody = {"embeddings": result}
resp.body = json.dumps(textbody)
resp.status = falcon.HTTP_200
def on_get(self, req, resp, algorithm_id):
"""Shows the representation of the selected algorithm
:param int algorithm_id: The id of the algorithm
"""
algorithm_dao = data_access.AlgorithmDAO()
algorithm, err = algorithm_dao.get_algorithm_by_id(algorithm_id)
if algorithm is None:
raise falcon.HTTPNotFound(message=str(err))
resp.body = json.dumps(algorithm)
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200
def on_get(self, req, resp):
"""Shows the representation of all algorithms available
"""
algorithm_dao = data_access.AlgorithmDAO()
algorithms, err = algorithm_dao.get_all_algorithms()
if algorithms is None:
raise falcon.HTTPNotFound(message=str(err))
resp.body = json.dumps(algorithms)
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200