How to use the pymongo.errors.OperationFailure function in pymongo

To help you get started, we’ve selected a few pymongo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mongodb / mongo-python-driver / test / View on Github external
def test_validate_collection(self):
        db = self.client.pymongo_test

        self.assertRaises(TypeError, db.validate_collection, 5)
        self.assertRaises(TypeError, db.validate_collection, None)

        db.test.insert_one({"dummy": u"object"})

        self.assertRaises(OperationFailure, db.validate_collection,
        self.assertRaises(OperationFailure, db.validate_collection,

        self.assertTrue(db.validate_collection(db.test, full=True))
        self.assertTrue(db.validate_collection(db.test, scandata=True))
        self.assertTrue(db.validate_collection(db.test, scandata=True, full=True))
        self.assertTrue(db.validate_collection(db.test, True, True))
github mongodb / motor / test / asyncio_tests / View on Github external
def test_fetch_next_exception(self):
        coll = self.collection
        cursor = coll.find()
        cursor.delegate._Cursor__id = 1234  # Not valid on server.

        with self.assertRaises(OperationFailure):
            yield from cursor.fetch_next

        # Avoid the cursor trying to close itself when it goes out of scope.
        cursor.delegate._Cursor__id = None
github CenterForOpenScience / / tests / View on Github external
def clear_transactions(self):
        except OperationFailure as error:
            message = utils.get_error_message(error)
            if messages.NO_TRANSACTION_ERROR not in message:
github shaypal5 / cachier / tests / View on Github external
def test_mongo_write_failure():
    """Testing MongoDB core handling of writing failure scenarios."""
    with pytest.raises(OperationFailure):
        val1 = _func_w_bad_mongo(1, 2)
        val2 = _func_w_bad_mongo(1, 2)
        assert val1 == val2
github pablito56 / pycourse / modules / View on Github external
# add one object to an array with push

edition = {
            'year': '1997',
            'editorial': 'planet'
db_replica.books.update({'_id': 'hobbit' }, {'$push': {'editions': edition}}) # quite similar to mongo shell

print db_replica.books.find_one({'_id': 'hobbit'})

# try to perform array operation over non-array element
    db_replica.books.update({'_id': 'lord_rings' }, {'$push': {'editions': edition}}) # non array operation
except OperationFailure as e:
    print e

# Create another edition
edition = {
            'year': '2001',
            'editorial': 'planet-lion'
db_replica.books.update({'_id': 'hobbit' }, {'$push': {'editions': edition}})

# Result ..
for edition in db_replica.books.find_one({'_id': 'hobbit'})['editions']:
    print edition

# How to update one document name inside array of object ?:
            {'_id': 'hobbit', # find document hobbit
github adewes / blitzdb / blitzdb / backends / mongo / View on Github external
def create_index(self, cls_or_collection, *args, **kwargs):
        if not isinstance(cls_or_collection, six.string_types):
            collection = self.get_collection_for_cls(cls_or_collection)
            collection = cls_or_collection

        if 'fields' not in kwargs:
            raise AttributeError("You must specify the 'fields' parameter when creating an index!")
        if 'opts' in kwargs:
            opts = kwargs['opts']
            opts = {}
            self.db[collection].ensure_index(list(kwargs['fields'].items()), **opts)
        except pymongo.errors.OperationFailure as failure:
            #The index already exists with different options, so we drop it and recreate it...
            self.db[collection].ensure_index(list(kwargs['fields'].items()), **opts)
github kernelci / kernelci-backend / app / utils / compare / View on Github external
:param collection: The name of the collection where to save the results.
    :type collection: str
    :param db_options: The database connection parameters.
    :type db_options: dict
    # Store the entire result from the comparison into a dedicated key.
    # When searching with the comparison ID, we just extract the "data" key
    # and return whatever has been saved there.
    json_obj["data"] = result

    database = utils.db.get_db_connection(db_options)
    doc_id = None

        ret_value, doc_id = database[collection].save(json_obj)
    except pymongo.errors.OperationFailure:
        utils.LOG.error("Error saving delta doc for %s", collection)

    return doc_id
github naparuba / opsbro / data / global-configuration / packs / mongodb / collectors / pymongo / View on Github external
def _legacy_write(self, sock_info, name, cmd, acknowledged, op_id,
                      bypass_doc_val, func, *args):
        """Internal legacy write helper."""
        # Cannot have both unacknowledged write and bypass document validation.
        if (bypass_doc_val and not acknowledged and
                    sock_info.max_wire_version >= 4):
            raise OperationFailure("Cannot set bypass_document_validation with"
                                   " unacknowledged write concern")
        listeners = self.database.client._event_listeners
        publish = listeners.enabled_for_commands

        if publish:
            start =
        rqst_id, msg, max_size = func(*args)
        if publish:
            duration = - start
                cmd,, rqst_id, sock_info.address, op_id)
            start =
            result = sock_info.legacy_write(
                rqst_id, msg, max_size, acknowledged)
        except Exception as exc:
github stone-payments / ansible-mongodb / library / View on Github external
if current_member is None:
                rs_config = rs_add_member(rs_config, member)
                rs_reconfigure(client, rs_config)
                return True
                return False
        elif state == 'absent':
            # check if given host is currently a member of replica set
            current_member = rs_get_member(rs_config, member['host'])
            if current_member:
                rs_config = rs_remove_member(rs_config, member)
                rs_reconfigure(client, rs_config)
                return True
                return False
    except OperationFailure as error:
        if error.code == 109:
            time.sleep(random.randint(2, 8))
        elif error.code == 103:
            raise OperationError(error)
        return rs_alter(client, member, state, tries+1)
github tranquilit / WAPT / lib / site-packages / pymongo / View on Github external
                if result == -1:
                    raise OperationFailure('Unknown kerberos '
                                           'failure in step function.')

                payload = kerberos.authGSSClientResponse(ctx) or ''

                cmd = SON([('saslContinue', 1),
                           ('conversationId', response['conversationId']),
                           ('payload', payload)])
                response = sock_info.command('$external', cmd)

                if result == kerberos.AUTH_GSS_COMPLETE:
                raise OperationFailure('Kerberos '
                                       'authentication failed to complete.')

            # Once the security context is established actually authenticate.
            # See RFC 4752, Section 3.1, last two paragraphs.
            if kerberos.authGSSClientUnwrap(ctx,
                                            str(response['payload'])) != 1:
                raise OperationFailure('Unknown kerberos '
                                       'failure during GSS_Unwrap step.')

            if kerberos.authGSSClientWrap(ctx,
                                          username) != 1:
                raise OperationFailure('Unknown kerberos '
                                       'failure during GSS_Wrap step.')

            payload = kerberos.authGSSClientResponse(ctx)