def register_user(schema: mongoengine.Document, account_id: object, chat_id: object) -> object: try: page_to_check = link_gen.generate_page_from_account(account_id) if not page_parsing.is_valid_page(page_to_check): raise RuntimeError( f'{page_to_check} for account {account_id} doesn\'t exist --> invalid account' ) if db_utils.check_account_exist(schema, chat_id): raise mongoengine.NotUniqueError(f'{chat_id} already exists') schema(chat_id=chat_id, account=account_id).save() return f'New user {str(chat_id)} : {account_id} saved' except (RuntimeError, mongoengine.NotUniqueError) as e: return f'{e}' except Exception as e: # Handling everything else return f'{e}'
def test_get_resource_manager_lock(self, mock_rm_lock, mock_worker, mock_datetime, mock_time): """ Assert that get_resource_manager_lock() attempts to save a lock to the database with the correct name, and that it creates a worker entry with that name and the correct timestamp, and that a failure to save the lock will cause it to sleep and retry acquisition. """ sender = RESOURCE_MANAGER_WORKER_NAME + '@' + platform.node() mock_rm_lock().save.side_effect = [mongoengine.NotUniqueError(), None] app.get_resource_manager_lock(sender) mock_worker.objects(name=sender).update_one.\ assert_called_with(set__last_heartbeat=mock_datetime.utcnow(), upsert=True) self.assertEquals(2, len(mock_rm_lock().save.mock_calls)) mock_time.sleep.assert_called_once_with(CELERY_CHECK_INTERVAL)
#!/usr/bin/env python import mongoengine from db_lib import * type_name = 'pin' for i in range(1, 25): containerName = "XtalPuck" + str(i) for j in range(0, 16): sampleName = "XtalSamp_" + str(i) + "_" + str(j) try: sampID = createSample(sampleName, sample_type=type_name) except mongoengine.NotUniqueError: raise mongoengine.NotUniqueError('{0}'.format(sampleName)) insertIntoContainer(containerName, j, sampID)
def save(self, validate=True, clean=True, **kwargs): """Save the :class:`Document` to the database. If the document already exists, it will be updated, otherwise it will be created. Args: validate (True): validates the document clean (True): call the document's clean method; requires ``validate`` to be True Returns: self """ # pylint: disable=no-member if self._meta.get("abstract"): raise mongoengine.InvalidDocumentError( "Cannot save an abstract document." ) if validate: self.validate(clean=clean) doc_id = self.to_mongo(fields=[self._meta["id_field"]]) created = "_id" not in doc_id or self._created # It might be refreshed by the pre_save_post_validation hook, e.g., for # etag generation doc = self.to_mongo() if self._meta.get("auto_create_index", True): self.ensure_indexes() try: # Save a new document or update an existing one if created: # Save new document # insert_one will provoke UniqueError alongside save does not # therefore, it need to catch and call replace_one. collection = self._get_collection() object_id = None if "_id" in doc: raw_object = collection.find_one_and_replace( {"_id": doc["_id"]}, doc ) if raw_object: object_id = doc["_id"] if not object_id: object_id = collection.insert_one(doc).inserted_id else: # Update existing document object_id = doc["_id"] created = False updates, removals = self._delta() update_doc = {} if updates: update_doc["$set"] = updates if removals: update_doc["$unset"] = removals if update_doc: updated_existing = self._update( object_id, update_doc, **kwargs ) if updated_existing is False: created = True # !!! This is bad, means we accidentally created a # new, potentially corrupted document. See # https://github.com/MongoEngine/mongoengine/issues/564 except pymongo.errors.DuplicateKeyError as err: message = "Tried to save duplicate unique keys (%s)" raise mongoengine.NotUniqueError(message % err) except pymongo.errors.OperationFailure as err: message = "Could not save document (%s)" if re.match("^E1100[01] duplicate key", str(err)): # E11000 - duplicate key error index # E11001 - duplicate key on update message = "Tried to save duplicate unique keys (%s)" raise mongoengine.NotUniqueError(message % err) raise mongoengine.OperationError(message % err) # Make sure we store the PK on this document now that it's saved id_field = self._meta["id_field"] if created or id_field not in self._meta.get("shard_key", []): self[id_field] = self._fields[id_field].to_python(object_id) self._clear_changed_fields() self._created = False return self