本文整理汇总了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
示例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
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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
示例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"})
示例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")
示例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")