當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。