Beispiel #1
0
def get_statements(result_type, method):
    """Get some statements constrained by query."""
    if result_type not in ApiCall.valid_result_types:
        return Response('Page not found.', 404)

    note_in_log(method=method, result_type=result_type)
    note_in_log(db_host=get_ro_host('primary'))

    if method == 'from_agents' and request.method == 'GET':
        call = FromAgentsApiCall(env)
    elif method == 'from_hashes' and request.method == 'POST':
        call = FromHashesApiCall(env)
    elif method.startswith('from_hash/') and request.method == 'GET':
        call = FromHashApiCall(env)
        call.web_query['hash'] = method[len('from_hash/'):]
    elif method == 'from_papers' and request.method == 'POST':
        call = FromPapersApiCall(env)
    elif method.startswith('from_paper/') and request.method == 'GET':
        try:
            _, id_type, id_val = method.split('/')
        except Exception as e:
            logger.error(f"Failed to parse paper ID: {method}")
            logger.exception(e)
            return abort(Response('Page not found.', 404))
        call = FromPapersApiCall(env)
        call.web_query['paper_ids'] = [{'type': id_type, 'id': id_val}]
    elif method == 'from_agent_json' and request.method == 'POST':
        call = FromAgentJsonApiCall(env)
    elif method == 'from_simple_json' and request.method == 'POST':
        call = FromSimpleJsonApiCall(env)
    else:
        logger.error(f'Invalid URL: {request.url}')
        return abort(404)

    return call.run(result_type=result_type)
Beispiel #2
0
def get_statements(result_type, method):
    """Get some statements constrained by query."""
    if result_type not in ApiCall.valid_result_types:
        return Response('Page not found.', 404)

    note_in_log(method=method, result_type=result_type)
    note_in_log(db_host=get_ro_host('primary'))

    if method == 'from_agents' and request.method == 'GET':
        call = FromAgentsApiCall(env)
    elif method == 'from_hashes' and request.method == 'POST':
        call = FromHashesApiCall(env)
    elif method.startswith('from_hash/') and request.method == 'GET':
        call = FromHashApiCall(env)
        call.web_query['hash'] = method[len('from_hash/'):]
    elif method == 'from_papers' and request.method == 'POST':
        call = FromPapersApiCall(env)
    elif method == 'from_agent_json' and request.method == 'POST':
        call = FromAgentJsonApiCall(env)
    elif method == 'from_query_json' and request.method == 'POST':
        call = FromQueryJsonApiCall(env)
    else:
        return abort(Response('Page not found.', 404))

    return call.run(result_type=result_type)
Beispiel #3
0
def get_statements(result_type, method):
    """Get some statements constrained by query."""
    if result_type not in ApiCall.valid_result_types:
        return Response("Page not found.", 404)

    note_in_log(method=method, result_type=result_type)
    note_in_log(db_host=get_ro_host("primary"))

    if method == "from_agents" and request.method == "GET":
        call = FromAgentsApiCall(env)
    elif method == "from_hashes" and request.method == "POST":
        call = FromHashesApiCall(env)
    elif method.startswith("from_hash/") and request.method == "GET":
        call = FromHashApiCall(env)
        call.web_query["hash"] = method[len("from_hash/"):]
    elif method == "from_papers" and request.method == "POST":
        call = FromPapersApiCall(env)
    elif method.startswith("from_paper/") and request.method == "GET":
        try:
            _, id_type, id_val = method.split("/")
        except Exception as e:
            logger.error(f"Failed to parse paper ID: {method}")
            logger.exception(e)
            return abort(Response("Page not found.", 404))
        call = FromPapersApiCall(env)
        call.web_query["paper_ids"] = [{"type": id_type, "id": id_val}]
    elif method == "from_agent_json" and request.method == "POST":
        call = FromAgentJsonApiCall(env)
    elif method == "from_simple_json" and request.method == "POST":
        call = FromSimpleJsonApiCall(env)
    else:
        logger.error(f"Invalid URL: {request.url}")
        return abort(404)

    return call.run(result_type=result_type)
Beispiel #4
0
    def get_db_query(self):
        if self.db_query is None:
            self.db_query = self._build_db_query()

            if not self.has['medscan']:
                minus_q = ~HasOnlySource('medscan')
                self.db_query &= minus_q
                if not self.ev_filter:
                    self.ev_filter = minus_q.ev_filter()
                else:
                    self.ev_filter &= minus_q.ev_filter()

            if self.strict:
                num_agents = (self.db_query.list_component_queries()
                              .count(HasAgent.__name__))
                self.db_query &= HasNumAgents((num_agents,))

            # Note the query in the log, if one is running.
            if is_log_running():
                note_in_log(query=self.db_query.to_json())

            logger.info(f"Constructed query \"{self.db_query}\":\n"
                        f"{json.dumps(self.db_query.to_json(), indent=2)}")

            # Prevent someone from breaking the database by querying too many
            # hashes, paper IDs, or MeshIds.
            query_set = set(self.db_query.list_component_queries())
            if {'HasHash', 'FromPapers', 'FromMeshIds'} & query_set:
                for q in self.db_query.iter_component_queries():
                    if isinstance(q, HasHash):
                        list_len = len(q.stmt_hashes)
                        lbl = 'hashes'
                    elif isinstance(q, FromPapers):
                        list_len = len(q.paper_list)
                        lbl = 'paper IDs'
                    elif isinstance(q, FromMeshIds):
                        list_len = len(q.mesh_ids)
                        lbl = 'MeSH IDs'
                    else:
                        list_len = 0
                        lbl = None

                    if list_len > MAX_LIST_LEN:
                        logger.error(f"Length exceeded: {list_len} > "
                                     f"{MAX_LIST_LEN}")
                        raise HttpUserError(f"Too many {lbl}! Only "
                                            f"{MAX_LIST_LEN} {lbl} allowed.")
        return self.db_query
Beispiel #5
0
    def get_db_query(self):
        if self.db_query is None:
            self.db_query = self._build_db_query()

            if not self.has['medscan']:
                minus_q = ~HasOnlySource('medscan')
                self.db_query &= minus_q
                if not self.ev_filter:
                    self.ev_filter = minus_q.ev_filter()
                else:
                    self.ev_filter &= minus_q.ev_filter()

            if self.strict:
                num_agents = (self.db_query.list_component_queries()
                              .count(HasAgent.__name__))
                self.db_query &= HasNumAgents((num_agents,))

            # Note the query in the log, if one is running.
            if is_log_running():
                note_in_log(query=self.db_query.to_json())

        logger.info(f"Constructed query \"{self.db_query}\":\n"
                    f"{json.dumps(self.db_query.to_json(), indent=2)}")
        return self.db_query
Beispiel #6
0
def get_statements_by_query_json(result_type):
    note_in_log(result_type=result_type)
    try:
        return DirectQueryApiCall(env).run(result_type)
    except ResultTypeError as e:
        return Response(f"Invalid result type: {e.result_type}", 400)
Beispiel #7
0
def get_statements_by_query_json(result_type):
    note_in_log(result_type=result_type)
    return FallbackQueryApiCall(env).run(result_type)