當前位置: 首頁>>代碼示例>>Python>>正文


Python errors.DuplicateKeyError方法代碼示例

本文整理匯總了Python中pymongo.errors.DuplicateKeyError方法的典型用法代碼示例。如果您正苦於以下問題:Python errors.DuplicateKeyError方法的具體用法?Python errors.DuplicateKeyError怎麽用?Python errors.DuplicateKeyError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pymongo.errors的用法示例。


在下文中一共展示了errors.DuplicateKeyError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_write_insert_version_duplicatekey

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def test_write_insert_version_duplicatekey():
    write_handler = Mock(write=Mock(__name__=""))
    vs = create_autospec(VersionStore, instance=True,
                         _collection=Mock(),
                         _version_nums=Mock(find_one_and_update=Mock(return_value={'version': 1})),
                         _versions=Mock(insert_one=Mock(__name__="insert_one"), find_one=Mock(__name__="find_one")),
                         _arctic_lib=create_autospec(ArcticLibraryBinding,
                                                     arctic=create_autospec(Arctic, mongo_host='some_host')))
    vs._insert_version = lambda version: VersionStore._insert_version(vs, version)
    vs._versions.insert_one.side_effect = [DuplicateKeyError("dup key error"), None]
    vs._collection.database.connection.nodes = []
    vs._write_handler.return_value = write_handler
    VersionStore.write(vs, 'sym', sentinel.data, prune_previous_version=False)
    assert vs._version_nums.find_one_and_update.call_count == 2
    assert vs._versions.find_one.call_count == 2
    assert write_handler.write.call_count == 2
    assert vs._versions.insert_one.call_count == 2 
開發者ID:man-group,項目名稱:arctic,代碼行數:19,代碼來源:test_version_store.py

示例2: test_append_insert_version_duplicatekey

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def test_append_insert_version_duplicatekey():
    read_handler = Mock(append=Mock(__name__=""))
    previous_version = TPL_VERSION.copy()
    previous_version['version'] = 1
    vs = create_autospec(VersionStore, instance=True,
                         _collection=Mock(),
                         _version_nums=Mock(find_one_and_update=Mock(return_value={'version': previous_version['version']+1})),
                         _versions=Mock(insert_one=Mock(__name__="insert_one"), find_one=Mock(__name__="find_one", return_value=previous_version)),
                         _arctic_lib=create_autospec(ArcticLibraryBinding,
                                                     arctic=create_autospec(Arctic, mongo_host='some_host')))
    vs._insert_version = lambda version: VersionStore._insert_version(vs, version)
    vs._versions.insert_one.side_effect = [DuplicateKeyError("dup key error"), None]
    vs._collection.database.connection.nodes = []
    vs._read_handler.return_value = read_handler
    VersionStore.append(vs, 'sym', [1, 2, 3], prune_previous_version=False, upsert=False)
    assert vs._version_nums.find_one_and_update.call_count == 2
    assert vs._versions.find_one.call_count == 2
    assert read_handler.append.call_count == 2
    assert vs._versions.insert_one.call_count == 2 
開發者ID:man-group,項目名稱:arctic,代碼行數:21,代碼來源:test_version_store.py

示例3: __flush_data

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def __flush_data(self, data):
        """Flush `data` to a chunk.
        """
        # Ensure the index, even if there's nothing to write, so
        # the filemd5 command always succeeds.
        self._ensure_index()

        if not data:
            return
        assert(len(data) <= self.chunk_size)

        chunk = {"files_id": self._file["_id"],
                 "n": self._chunk_number,
                 "data": Binary(data)}

        try:
            self._chunks.insert(chunk)
        except DuplicateKeyError:
            self._raise_file_exists(self._file['_id'])
        self._chunk_number += 1
        self._position += len(data) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:grid_file.py

示例4: inc

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def inc(op: str, ident: str, period_secs: int, max_operations: int):
  coll = db.coll('opcount')
  cur_time = int(time.time())
  begin_at = datetime.datetime.utcfromtimestamp(cur_time - cur_time % period_secs)
  expire_at = begin_at + datetime.timedelta(seconds=period_secs)
  try:
    doc = await coll.find_one_and_update(filter={'ident': ident,
                                                 'begin_at': begin_at,
                                                 'expire_at': expire_at,
                                                 op: {'$not': {'$gte': max_operations}}},
                                         update={'$inc': {op: 1}},
                                         upsert=True,
                                         return_document=ReturnDocument.AFTER)
    return doc
  except errors.DuplicateKeyError:
    raise error.OpcountExceededError(op, period_secs, max_operations) 
開發者ID:vijos,項目名稱:vj4,代碼行數:18,代碼來源:opcount.py

示例5: add

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def add(domain_id: str, owner_uid: int,
              roles=builtin.DOMAIN_SYSTEM['roles'],
              name: str=None, gravatar: str=None, bulletin: str=''):
  validator.check_domain_id(domain_id)
  validator.check_name(name)
  validator.check_bulletin(bulletin)
  for domain in builtin.DOMAINS:
    if domain['_id'] == domain_id:
      raise error.DomainAlreadyExistError(domain_id)
  coll = db.coll('domain')
  try:
    result = await coll.insert_one({'_id': domain_id,
                                    'pending': True, 'owner_uid': owner_uid,
                                    'roles': roles, 'name': name,
                                    'gravatar': gravatar, 'bulletin': bulletin})
    domain_id = result.inserted_id
  except errors.DuplicateKeyError:
    raise error.DomainAlreadyExistError(domain_id) from None
  # grant root role to owner by default
  await add_user_role(domain_id, owner_uid, builtin.ROLE_ROOT)
  await coll.update_one({'_id': domain_id},
                        {'$unset': {'pending': ''}})
  return domain_id 
開發者ID:vijos,項目名稱:vj4,代碼行數:25,代碼來源:domain.py

示例6: _acquire

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def _acquire(self):
        ttl = datetime.now() + timedelta(seconds=self._lease_time)
        try:
            self.collection.insert({
                '_id': self.lock_name,
                'ttl': ttl,
                'client_id': self._client_id},
                w=1, j=1)
        except errors.DuplicateKeyError:
            self.collection.remove(
                {"_id": self.lock_name, 'ttl': {'$lt': datetime.now()}})
            try:
                self.collection.insert(
                    {'_id': self.lock_name,
                     'ttl': ttl,
                     'client_id': self._client_id}, w=1, j=1)
            except errors.DuplicateKeyError:
                self._locked = False
                return self._locked
        self._lock_expires = ttl
        self._locked = True
        return self._locked 
開發者ID:ydf0509,項目名稱:distributed_framework,代碼行數:24,代碼來源:lock.py

示例7: add_user

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def add_user(self, user_obj):
        """Add a user object to the database

            Args:
                user_obj(scout.models.User): A dictionary with user information

            Returns:
                user_info(dict): a copy of what was inserted
        """
        LOG.info("Adding user %s to the database", user_obj["email"])
        if not "_id" in user_obj:
            user_obj["_id"] = user_obj["email"]

        try:
            self.user_collection.insert_one(user_obj)
            LOG.debug("User inserted")
        except DuplicateKeyError as err:
            raise IntegrityError("User {} already exists in database".format(user_obj["email"]))

        return user_obj 
開發者ID:Clinical-Genomics,項目名稱:scout,代碼行數:22,代碼來源:user.py

示例8: upsert_variant

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def upsert_variant(self, variant_obj):
        """Load a variant object, if the object already exists update compounds.

        Args:
            variant_obj(dict)

        Returns:
            result
        """
        LOG.debug("Upserting variant %s", variant_obj["_id"])
        try:
            result = self.variant_collection.insert_one(variant_obj)
        except DuplicateKeyError as err:
            LOG.debug("Variant %s already exists in database", variant_obj["_id"])
            result = self.variant_collection.find_one_and_update(
                {"_id": variant_obj["_id"]},
                {"$set": {"compounds": variant_obj.get("compounds", [])}},
            )
            variant = self.variant_collection.find_one({"_id": variant_obj["_id"]})
        return result 
開發者ID:Clinical-Genomics,項目名稱:scout,代碼行數:22,代碼來源:variant_loader.py

示例9: load_variant_bulk

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def load_variant_bulk(self, variants):
        """Load a bulk of variants

        Args:
            variants(iterable(scout.models.Variant))

        Returns:
            object_ids
        """
        if len(variants) == 0:
            return

        LOG.debug("Loading variant bulk")
        try:
            result = self.variant_collection.insert_many(variants)
        except (DuplicateKeyError, BulkWriteError) as err:
            # If the bulk write is wrong there are probably some variants already existing
            # In the database. So insert each variant
            for var_obj in variants:
                try:
                    self.upsert_variant(var_obj)
                except IntegrityError as err:
                    pass

        return 
開發者ID:Clinical-Genomics,項目名稱:scout,代碼行數:27,代碼來源:variant_loader.py

示例10: load_hpo_bulk

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def load_hpo_bulk(self, hpo_bulk):
        """Add a hpo object

        Arguments:
            hpo_bulk(list(scout.models.HpoTerm))

        Returns:
            result: pymongo bulkwrite result

        """
        LOG.debug("Loading hpo bulk")

        try:
            result = self.hpo_term_collection.insert_many(hpo_bulk)
        except (DuplicateKeyError, BulkWriteError) as err:
            raise IntegrityError(err)
        return result 
開發者ID:Clinical-Genomics,項目名稱:scout,代碼行數:19,代碼來源:hpo.py

示例11: load_hgnc_bulk

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def load_hgnc_bulk(self, gene_objs):
        """Load a bulk of hgnc gene objects

        Raises IntegrityError if there are any write concerns

        Args:
            gene_objs(iterable(scout.models.hgnc_gene))

        Returns:
            result (pymongo.results.InsertManyResult)
        """

        LOG.info("Loading gene bulk with length %s", len(gene_objs))
        try:
            result = self.hgnc_collection.insert_many(gene_objs)
        except (DuplicateKeyError, BulkWriteError) as err:
            raise IntegrityError(err)

        return result 
開發者ID:Clinical-Genomics,項目名稱:scout,代碼行數:21,代碼來源:hgnc.py

示例12: create

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def create(self, value, collection, enable_update_if_current=False):
        dbcol = self.db[collection]
        txn_k = update_if_current.SERIAL_TXN_COUNTER_KEY

        if enable_update_if_current:
            update_if_current.enable_check_for(value)

        serial = value.serialize()
        if hasattr(value, txn_k):
            serial[txn_k] = 0
            setattr(value, txn_k, 0)

        try:
            id_or_error = dbcol.insert(serial, getLastError=1)
            if isinstance(id_or_error, basestring) \
                and '_id' in serial and id_or_error != serial['_id']:
                raise BiiStoreException(id_or_error)
            return id_or_error
        except DuplicateKeyError as e:
            raise AlreadyInStoreException(e)
        except Exception as e:
            logger.error(traceback.format_exc())
            raise e 
開發者ID:biicode,項目名稱:bii-server,代碼行數:25,代碼來源:mongo_store.py

示例13: _request_transaction

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def _request_transaction(self, collection, entity_name, brl):
        transaction_definition = {'_id': brl.serialize(),
                                  'state': 'initial'}
        dbcol = self.db[collection]

        try:
            id_or_error = dbcol.insert(transaction_definition, getLastError=1)
        except DuplicateKeyError:
            raise BiiPendingTransactionException('There\'s a pending transaction for %s %s'
                                                ', please retry later'
                                                % (entity_name, transaction_definition['_id']))

        if isinstance(id_or_error, basestring) \
             and id_or_error != transaction_definition['_id']:
            raise BiiPendingTransactionException('There\'s a pending transaction for %s %s'
                                                + ', please retry later'
                                                % (entity_name, transaction_definition['_id']))
        return dbcol.find_one({'_id': transaction_definition['_id'], 'state': "initial"}) 
開發者ID:biicode,項目名稱:bii-server,代碼行數:20,代碼來源:mongo_store.py

示例14: post

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def post(self, token: AccessToken.Payload):

        try:
            request_json = UserCreateSchema().load(request.get_json())
        except ValidationError as e:
            raise errors.InvalidRequestJSON(e.messages)

        # generate password hash
        password = request_json.pop("password")
        request_json["password_hash"] = generate_password_hash(password)

        # fetch permissions
        request_json["scope"] = ROLES.get(request_json.pop("role"))

        try:
            user_id = Users().insert_one(request_json).inserted_id
            return jsonify({"_id": user_id})
        except DuplicateKeyError:
            raise errors.BadRequest("User already exists") 
開發者ID:openzim,項目名稱:zimfarm,代碼行數:21,代碼來源:user.py

示例15: _insert_version

# 需要導入模塊: from pymongo import errors [as 別名]
# 或者: from pymongo.errors import DuplicateKeyError [as 別名]
def _insert_version(self, version):
        try:
            # Keep here the mongo_retry to avoid incrementing versions and polluting the DB with garbage segments,
            # upon intermittent Mongo errors
            # If, however, we get a DuplicateKeyError, suppress it and raise OperationFailure, so that the method-scoped
            # mongo_retry re-tries and creates a new version, to overcome the issue.
            mongo_retry(self._versions.insert_one)(version)
        except DuplicateKeyError as err:
            logger.exception(err)
            raise OperationFailure("A version with the same _id exists, force a clean retry") 
開發者ID:man-group,項目名稱:arctic,代碼行數:12,代碼來源:version_store.py


注:本文中的pymongo.errors.DuplicateKeyError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。