예제 #1
0
    def on_post(self, req, resp, dataset_id, dataset_dto):
        """Return suggests to use with autocomplete

        This method will return suggestions to be used on frontend while users
        input the entity name.

        TODO: this should only return entities that exists on dataset, right
        now returns all possible entities.

        :param int dataset_id: The id of the dataset to autocomplete
        :param DTO dataset_dto: The Dataset DTO from dataset_id (from hook)
        :param str input: The input to autocomplete (from body)
        :returns: A list with entities and full text
        :rtype: Object
        """
        try:
            body = common_hooks.read_body_as_json(req)
            input_text = body['input']
        except KeyError as err:
            raise falcon.HTTPMissingParam("input")
        entity_dao = data_access.EntityDAO(dataset_dto.dataset_type,
                                           dataset_id)

        # Extract suggestion from elasticsearch
        suggestion = entity_dao.suggest_entity(input_text)

        # Return a response
        resp.body = json.dumps(suggestion)
        resp.content_type = 'application/json'
        resp.status = falcon.HTTP_200
예제 #2
0
def read_vector_from_body(req, resp, resource, params):
    """This returns a list of entities"""
    try:
        body = common_hooks.read_body_as_json(req)

        if not isinstance(body["entities"], list):
            raise falcon.HTTPInvalidParam(
                "The param 'distance' must contain a list", "entities")

        # Redefine variables
        params["entities"] = body["entities"]

    except KeyError as err:
        raise falcon.HTTPMissingParam(str(err))
예제 #3
0
def read_http_dataset_dto(req, resp, resource, params):
    """Returns a HTTPUserDatasetDTO"""
    try:
        body = common_hooks.read_body_as_json(req)
        params["dataset_info"] = HTTPUserDatasetDTO()

        if "name" in body:
            params["dataset_info"].name = body["name"]
        if "description" in body:
            params["dataset_info"].description = body["description"]
    except KeyError as err:
        raise falcon.HTTPBadRequest(
            title="Invalid params",
            description=("Some of the required params ({}) "
                         "are not present").format(str(err)))
예제 #4
0
def read_pair_list(req, resp, resource, params):
    try:
        body = common_hooks.read_body_as_json(req)

        if "distance" not in body:
            raise falcon.HTTPMissingParam("distance")

        if not isinstance(body["distance"], list) and\
           len(body["distance"]) != 2:
            msg = ("The param 'distance' must contain a list of two"
                   "entities.")
            raise falcon.HTTPInvalidParam(msg, "distance")

        params["entities_pair"] = (body["distance"][0], body["distance"][1])

    except KeyError as err:
        raise falcon.HTTPMissingParam(err(str))
예제 #5
0
def read_body_generate_triples(req, resp, resource, params):
    try:
        body = common_hooks.read_body_as_json(req)

        params['gen_triples_param'] = body['generate_triples']
        if "levels" not in params['gen_triples_param']:
            msg = ("The 'generate_triples' JSON object must contain"
                   "level attribute")
            raise falcon.HTTPInvalidParam(msg, "levels")
        elif isinstance(params['gen_triples_param']['levels'], str):
            try:
                params['gen_triples_param']['levels'] = int(
                    params['gen_triples_param']['levels'], 10)
            except ValueError as err:
                msg = ("The 'levels' attribute must be an integer")
                raise falcon.HTTPInvalidParam(msg, "levels")
    except KeyError as err:
        raise falcon.HTTPMissingParam(err(str))
예제 #6
0
def read_triples_from_body(req, resp, resource, params):
    """Reads a list of triples"""
    try:
        body = common_hooks.read_body_as_json(req)
        params["triples_list"] = []
        for triple in body:
            new_triple = {
                "subject": {
                    "value": triple["subject"]
                },
                "predicate": {
                    "value": triple["predicate"]
                },
                "object": {
                    "value": triple["object"]
                }
            }
            params["triples_list"].append(new_triple)

    except KeyError as err:
        raise falcon.HTTPInvalidParam(msg="Invalid body params",
                                      param_name=str(err))
예제 #7
0
    def on_post(self, req, resp, dataset_id, dataset_dto):
        """Generates an autocomplete index with desired lang

        This request may take long time to complete, so it uses tasks.

        :query list langs: A list with languages to be requested
        :param id dataset_id: The dataset to insert triples into
        :param DTO dataset_dto: The Dataset DTO from dataset_id (from hook)
        """
        try:
            body = common_hooks.read_body_as_json(req)
            languages = body['langs']
            if not isinstance(languages, list):
                raise falcon.HTTPInvalidParam(
                    ("A list with languages in ISO 639-1 code was expected"),
                    "langs")
        except KeyError as err:
            raise falcon.HTTPMissingParam("langs")

        entity_dao = data_access.EntityDAO(dataset_dto.dataset_type,
                                           dataset_id)
        # Call to the task
        task = async_tasks.build_autocomplete_index.delay(dataset_id,
                                                          langs=languages)
        # Create the new task
        task_dao = data_access.TaskDAO()
        task_obj, err = task_dao.add_task_by_uuid(task.id)
        if task_obj is None:
            raise falcon.HTTPNotFound(description=str(err))
        task_obj["next"] = "/datasets/" + dataset_id
        task_dao.update_task(task_obj)

        msg = "Task {} created successfuly".format(task_obj['id'])
        textbody = {"status": 202, "message": msg}
        resp.location = "/tasks/" + str(task_obj['id'])
        resp.body = json.dumps(textbody)
        resp.content_type = 'application/json'
        resp.status = falcon.HTTP_202