当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.NotFoundError方法代码示例

本文整理汇总了Python中elasticsearch.exceptions.NotFoundError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NotFoundError方法的具体用法?Python exceptions.NotFoundError怎么用?Python exceptions.NotFoundError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在elasticsearch.exceptions的用法示例。


在下文中一共展示了exceptions.NotFoundError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: retrieve

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def retrieve(self, request, pk, version):
        """
        Return a single course by ID
        """
        # Wrap the ES get in a try/catch to we control the exception we emit — it would
        # raise and end up in a 500 error otherwise
        try:
            query_response = ES_CLIENT.get(
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                id=pk,
            )
        except NotFoundError:
            return Response(status=404)

        # Format a clean course object as a response
        return Response(self._meta.indexer.format_es_object_for_api(query_response)) 
开发者ID:openfun,项目名称:richie,代码行数:19,代码来源:courses.py

示例2: get

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def get(self, index, id, doc_type='_all', params=None):
        result = None
        if index in self.__documents_dict:
            result = self.find_document(doc_type, id, index, result)

        if result:
            result['found'] = True
        else:
            error_data = {
                '_index': index,
                '_type': doc_type,
                '_id': id,
                'found': False
            }
            raise NotFoundError(404, json.dumps(error_data))

        return result 
开发者ID:apache,项目名称:airflow,代码行数:19,代码来源:fake_elasticsearch.py

示例3: delete

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def delete(self, index, doc_type, id, params=None):

        found = False

        if index in self.__documents_dict:
            for document in self.__documents_dict[index]:
                if document.get('_type') == doc_type and document.get('_id') == id:
                    found = True
                    self.__documents_dict[index].remove(document)
                    break

        result_dict = {
            'found': found,
            '_index': index,
            '_type': doc_type,
            '_id': id,
            '_version': 1,
        }

        if found:
            return result_dict
        else:
            raise NotFoundError(404, json.dumps(result_dict)) 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:fake_elasticsearch.py

示例4: suggest

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def suggest(self, body, index=None):
        if index is not None and index not in self.__documents_dict:
            raise NotFoundError(404, 'IndexMissingException[[{0}] missing]'.format(index))

        result_dict = {}
        for key, value in body.items():
            text = value.get('text')
            suggestion = int(text) + 1 if isinstance(text, int) \
                else '{0}_suggestion'.format(text)
            result_dict[key] = [
                {
                    'text': text,
                    'length': 1,
                    'options': [
                        {
                            'text': suggestion,
                            'freq': 1,
                            'score': 1.0
                        }
                    ],
                    'offset': 0
                }
            ]
        return result_dict 
开发者ID:apache,项目名称:airflow,代码行数:26,代码来源:fake_elasticsearch.py

示例5: _normalize_index_to_list

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def _normalize_index_to_list(self, index):
        # Ensure to have a list of index
        if index is None:
            searchable_indexes = self.__documents_dict.keys()
        elif isinstance(index, str):
            searchable_indexes = [index]
        elif isinstance(index, list):
            searchable_indexes = index
        else:
            # Is it the correct exception to use ?
            raise ValueError("Invalid param 'index'")

        # Check index(es) exists
        for searchable_index in searchable_indexes:
            if searchable_index not in self.__documents_dict:
                raise NotFoundError(404,
                                    'IndexMissingException[[{0}] missing]'
                                    .format(searchable_index))

        return searchable_indexes 
开发者ID:apache,项目名称:airflow,代码行数:22,代码来源:fake_elasticsearch.py

示例6: find_missing_types

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def find_missing_types(index_type_mapping):
    """Find if doc types are not exist in given indices"""
    missing_index, missing_type = [], []

    if not index_type_mapping:
        return missing_index, missing_type

    es_engine = searchlight.elasticsearch.get_api()

    for index in index_type_mapping.keys():
        for doc_type in index_type_mapping[index]:
            try:
                mapping = es_engine.indices.get_mapping(index, doc_type)
                if not mapping:
                    missing_type.append(doc_type)
            except es_exc.NotFoundError:
                missing_index.append(index)

    return set(missing_index), set(missing_type) 
开发者ID:openstack,项目名称:searchlight,代码行数:21,代码来源:utils.py

示例7: delete

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def delete(self, event_type, payload, timestamp):
        zone_id = payload['id']
        version = self.get_version(payload, timestamp,
                                   preferred_date_field='deleted_at')
        delete_recordset = self.recordset_helper.delete_documents_with_parent(
            zone_id,
            version=version)
        items = [pipeline.DeleteItem(
            self.recordset_helper.plugin,
            event_type,
            payload,
            rs['_id']) for rs in delete_recordset]

        try:
            self.index_helper.delete_document(
                {'_id': zone_id, '_version': version})
            items.append(pipeline.DeleteItem(self.index_helper.plugin,
                                             event_type,
                                             payload,
                                             zone_id))
        except exceptions.NotFoundError:
            msg = "Zone %s not found when deleting"
            LOG.error(msg, zone_id)
        return items 
开发者ID:openstack,项目名称:searchlight,代码行数:26,代码来源:notification_handlers.py

示例8: needs_es

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def needs_es(index_name=None):
    def inner_function(function=None):
        @wraps(function)
        def wrapper(*args, **kwargs):
            if index_name is not None:
                # TODO pre-check, might not be necessary
                pass
            try:
                return function(*args, **kwargs)
            except NotFoundError as e:
                not_found = getattr(e, "info", {}).get("error", {}).get("root_cause", [{}])[0].get("resource.id", None)
                message = "The required index does not exist in this ElasticSearch database"
                if not_found is not None:
                    message = message + " (" + str(not_found) + ")"
                abort(404, message)
        return wrapper

    if index_name is not None and not isinstance(index_name, str):
        return inner_function(index_name)
    else:
        return inner_function 
开发者ID:bitshares,项目名称:bitshares-explorer-api,代码行数:23,代码来源:utils.py

示例9: retrieve

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def retrieve(self, request, pk, version, kind):
        """
        Return a single item by ID
        """
        # Wrap the ES get in a try/catch to we control the exception we emit — it would
        # raise and end up in a 500 error otherwise
        try:
            query_response = ES_CLIENT.get(
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                id=pk,
            )
        except NotFoundError:
            raise NotFound

        # Format a clean category object as a response
        return Response(
            self._meta.indexer.format_es_object_for_api(
                query_response,
                # Get the best language we can return multilingual fields in
                get_language_from_request(request),
            )
        ) 
开发者ID:openfun,项目名称:richie,代码行数:25,代码来源:categories.py

示例10: retrieve

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def retrieve(self, request, pk, version):
        """
        Return a single person by ID
        """
        # Wrap the ES get in a try/catch so we control the exception we emit — it would
        # raise and end up in a 500 error otherwise
        try:
            query_response = ES_CLIENT.get(
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                id=pk,
            )
        except NotFoundError:
            return Response(status=404)

        # Format a clean person object as a response
        return Response(
            self._meta.indexer.format_es_object_for_api(
                query_response,
                # Get the best language we can return multilingual fields in
                get_language_from_request(request),
            )
        ) 
开发者ID:openfun,项目名称:richie,代码行数:25,代码来源:persons.py

示例11: retrieve

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def retrieve(self, request, pk, version):
        """
        Return a single organization by ID
        """
        # Wrap the ES get in a try/catch so we control the exception we emit — it would
        # raise and end up in a 500 error otherwise
        try:
            query_response = ES_CLIENT.get(
                index=self._meta.indexer.index_name,
                doc_type=self._meta.indexer.document_type,
                id=pk,
            )
        except NotFoundError:
            return Response(status=404)

        # Format a clean organization object as a response
        return Response(
            self._meta.indexer.format_es_object_for_api(
                query_response,
                # Get the best language we can return multilingual fields in
                get_language_from_request(request),
            )
        ) 
开发者ID:openfun,项目名称:richie,代码行数:25,代码来源:organizations.py

示例12: _load_latest_logs

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def _load_latest_logs(self, performer_id, repository_id, account_id, filter_kinds, size):
        """
        Return the latest logs from Elasticsearch.

        Look at indices up to theset logrotateworker threshold, or up to 30 days if not defined.
        """
        # Set the last index to check to be the logrotateworker threshold, or 30 days
        end_datetime = datetime.now()
        start_datetime = end_datetime - timedelta(days=DATE_RANGE_LIMIT)

        latest_logs = []
        for day in _date_range_descending(start_datetime, end_datetime, includes_end_datetime=True):
            try:
                logs = self._load_logs_for_day(
                    day, performer_id, repository_id, account_id, filter_kinds, size=size
                )
                latest_logs.extend(logs)
            except NotFoundError:
                continue

            if len(latest_logs) >= size:
                break

        return _for_elasticsearch_logs(latest_logs[:size], repository_id, account_id) 
开发者ID:quay,项目名称:quay,代码行数:26,代码来源:document_logs_model.py

示例13: count

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def count(self, indices):
        """Count number of documents.

        Args:
            indices: List of indices.

        Returns:
            Number of documents.
        """
        if not indices:
            return 0
        try:
            result = self.client.count(index=indices)
        except (NotFoundError, RequestError) as e:
            es_logger.error(
                'Unable to count indexes (index not found), with '
                'error: {0!s}'.format(e))
            return 0
        return result.get('count', 0) 
开发者ID:google,项目名称:timesketch,代码行数:21,代码来源:elastic.py

示例14: delete_index_item

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def delete_index_item(item, model_name, refresh=True):
    '''
    Deletes an item from the index.
    :param item: must be a serializable object.
    :param model_name: doctype, which must also be the model name.
    :param refresh: a boolean that determines whether to refresh the index, making all operations performed since the last refresh
    immediately available for search, instead of needing to wait for the scheduled Elasticsearch execution. Defaults to True.
    '''
    src = Bungiesearch()

    logger.info('Getting index for model {}.'.format(model_name))
    for index_name in src.get_index(model_name):
        index_instance = src.get_model_index(model_name)
        item_es_id = index_instance.fields['_id'].value(item)
        try:
            src.get_es_instance().delete(index_name, model_name, item_es_id)
        except NotFoundError as e:
            logger.warning('NotFoundError: could not delete {}.{} from index {}: {}.'.format(model_name, item_es_id, index_name, str(e)))

        if refresh:
            src.get_es_instance().indices.refresh(index=index_name) 
开发者ID:ChristopherRabotin,项目名称:bungiesearch,代码行数:23,代码来源:utils.py

示例15: get

# 需要导入模块: from elasticsearch import exceptions [as 别名]
# 或者: from elasticsearch.exceptions import NotFoundError [as 别名]
def get(self, request, format=None):
        # TODO: catch all exception. At the very least, deal with 404 not found and
        # connection refused exceptions.
        # Temporarily remove exceptions for debugging.
        try:
            trail_ids = [x["key"] for x in self.es.search(index=self.index, body={
                "aggs" : {
                    "trail_id" : {
                        "terms" : { "field" : "trail_id" }
                    }
                }
            })["aggregations"]["trail_id"]["buckets"]]
            response = self.create_trails(trail_ids)
        except ConnectionError as e:
            raise OSError("Failed to connect to local elasticsearch instance.")
        except NotFoundError:
            raise DataWakeIndexUnavailable
        return Response(response) 
开发者ID:nasa-jpl-memex,项目名称:memex-explorer,代码行数:20,代码来源:rest.py


注:本文中的elasticsearch.exceptions.NotFoundError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。