How to use the pymongo.errors.ConnectionFailure 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 / test_client.py View on Github external
collection.drop()
        collection.insert_many([{} for _ in range(200)])  # More than one batch.
        pool = get_pool(client)
        pool._check_interval_seconds = None  # Never check.

        cursor = collection.find(cursor_type=CursorType.EXHAUST)

        # Initial query succeeds.
        cursor.next()

        # Cause a network error.
        sock_info = cursor._Cursor__exhaust_mgr.sock
        sock_info.sock.close()

        # A getmore fails.
        self.assertRaises(ConnectionFailure, list, cursor)
        self.assertTrue(sock_info.closed)

        # The socket was closed and the semaphore was decremented.
        self.assertNotIn(sock_info, pool.sockets)
        self.assertTrue(pool._socket_semaphore.acquire(blocking=False))
github mongodb / motor / test / asyncio_tests / test_asyncio_ipv6.py View on Github external
def test_ipv6(self):
        assert env.host in ('localhost', '127.0.0.1'), (
            "This unittest isn't written to test IPv6 "
            "with host %s" % repr(env.host))

        try:
            connected(MongoClient("[::1]",
                                  username=db_user,
                                  password=db_password,
                                  serverSelectionTimeoutMS=100))
        except ConnectionFailure:
            # Either mongod was started without --ipv6
            # or the OS doesn't support it (or both).
            raise SkipTest("No IPV6")

        if test.env.auth:
            cx_string = 'mongodb://%s:%s@[::1]:%d' % (
                db_user, db_password, env.port)
        else:
            cx_string = 'mongodb://[::1]:%d' % env.port

        cx = self.asyncio_client(uri=cx_string)
        collection = cx.motor_test.test_collection
        yield from collection.insert_one({"dummy": "object"})
        self.assertTrue((yield from collection.find_one({"dummy": "object"})))
github bigchaindb / bigchaindb / bigchaindb / backend / localmongodb / connection.py View on Github external
serverselectiontimeoutms=self.connection_timeout,
                                             ssl=self.ssl,
                                             ssl_ca_certs=self.ca_cert,
                                             ssl_certfile=self.certfile,
                                             ssl_keyfile=self.keyfile,
                                             ssl_pem_passphrase=self.keyfile_passphrase,
                                             ssl_crlfile=self.crlfile,
                                             ssl_cert_reqs=CERT_REQUIRED,
                                             **MONGO_OPTS)
                if self.login is not None:
                    client[self.dbname].authenticate(self.login,
                                                     mechanism='MONGODB-X509')

            return client

        except (pymongo.errors.ConnectionFailure,
                pymongo.errors.OperationFailure) as exc:
            logger.info('Exception in _connect(): {}'.format(exc))
            raise ConnectionError(str(exc)) from exc
        except pymongo.errors.ConfigurationError as exc:
            raise ConfigurationError from exc
github vnpy / vnpy / examples / RQData / run.py View on Github external
def connectMongo(self):
        """连接数据库"""
        try:
            self.client = MongoClient(serverSelectionTimeoutMS=10)
            self.client.server_info()
            self.writeLog(u'MongoDB连接成功')
            return True
        except ConnectionFailure:
            self.client = None
            self.writeLog(u'MongoDB连接失败')
            return False
github mulhod / reviewer_experience_prediction / util / extract_features.py View on Github external
logdebug('Project directory: {0}'.format(project_dir))
    logdebug('Binarize features? {0}'.format(binarize))
    logdebug('Try to reuse previously-extracted features in the database? {0}'
             .format(reuse_features))
    logdebug('Lower-case text as part of the normalization step? {0}'
             .format(lowercase_text))
    logdebug('Lower-case character n-grams during feature extraction? {0}'
             .format(lowercase_cngrams))
    logdebug('Batch size for database updates: {0}'.format(update_batch_size))

    # Establish connection to MongoDB database collection
    loginfo('Connecting to MongoDB database on mongodb://{0}:{1}...'
            .format(mongodb_host, mongodb_port))
    try:
        db = connect_to_db(host=mongodb_host, port=mongodb_port)
    except ConnectionFailure as e:
        logerr('Unable to connect to MongoDB reviews collection.')
        logerr(e)
        raise e
    db.write_concern['w'] = 0

    # Get list of games
    game_files = get_game_files(game_files)

    # Iterate over the game files, extracting and adding/replacing
    # features to the database
    for game_file in game_files:
        game = splitext(game_file)[0]
        if partition == 'all':
            partition_string = ' from the "training" and "test" data partitions'
        else:
            partition_string = ' from the "{0}" data partition'.format(partition)
github naparuba / opsbro / data / global-configuration / packs / mongodb / collectors / pymongo / mongo_client.py View on Github external
def _is_writable(self):
        """Attempt to connect to a writable server, or return False.
        """
        topology = self._get_topology()  # Starts monitors if necessary.
        try:
            svr = topology.select_server(writable_server_selector)

            # When directly connected to a secondary, arbiter, etc.,
            # select_server returns it, whatever the selector. Check
            # again if the server is writable.
            return svr.description.is_writable
        except ConnectionFailure:
            return False
github felinx / poweredsites / poweredsites / db / mongodb.py View on Github external
def connect():
    try:
        con = Connection(host=options.mongodb['host'], port=int(options.mongodb['port']))
    except ConnectionFailure:
        raise DBConnectionError('Unable to connect to MongoDB')

    mongodb = con[options.mongodb['database']]
    auth = mongodb.authenticate(options.mongodb['user'], options.mongodb['password'])
    if not auth:
        raise DBAuthenticatedError('Authentication to MongoDB failed')

    conn.mongodb = mongodb
github DreamingRaven / nemesyst / archive / Misc / initUser.py View on Github external
try:
    # creating database admin
    print(prePend, "CREATING: ", args['user'], " DB: ", args['name'], " Role: ", args['role'])
    client = MongoClient(args['url'])  # dbUrl)
    db = client[args['name']]
    db.command("createUser", args['user'], pwd=args['pass'], roles=[args['role']])

except OSError as err:

    print(prePend, "OS error: {0}".format(err))

except ValueError:

    print(prePend, sys.exc_info()[0])

except errors.ConnectionFailure:
    print(prePend, "Could not communicate with database: ", sys.exc_info()[0])

except errors.DuplicateKeyError:
    print(prePend, "Error, you are trying to add something that already exists: ", sys.exc_info()[0])
except errors.InvalidName:
    print(prePend, "Error invalid name: (probably username or databaseName)", sys.exc_info()[0])

except:

    # dunno what the error is, may {deity} have mercy on your poor soul
    print(prePend, "unexpected error, mongod could already be running!: ", sys.exc_info()[0])

print(prePend, "Fin.", (time.time() - startTime), " seconds.")
github smartbgp / yabgp / yabgp / db / mongodb.py View on Github external
def _get_db(self):
        """
        get database
        :return: database
        """
        try:
            if self.use_replica:  # if use replica set configuration
                connection = pymongo.MongoClient(
                    self.conection_url, replicaSet=self.replica_name)
            else:  # use for standalone node or mongos in sharded setup
                connection = pymongo.MongoClient(self.conection_url)

        except pymongo.errors.ConnectionFailure as e:
            LOG.warn('Unable to connect to the database server, %s', e)
            raise

        database = getattr(connection, self.db_name)
        return database
github Clinical-Genomics / scout / scout / adapter / client.py View on Github external
authdb = authdb or mongodb
    if uri is None:
        if username and password:
            uri = "mongodb://{}:{}@{}:{}/{}".format(
                quote_plus(username), quote_plus(password), host, port, authdb
            )
            log_uri = "mongodb://{}:****@{}:{}/{}".format(quote_plus(username), host, port, authdb)
        else:
            log_uri = uri = "mongodb://%s:%s" % (host, port)

    LOG.info("Try to connect to %s" % log_uri)
    try:
        client = MongoClient(uri, serverSelectionTimeoutMS=timeout)
    except ServerSelectionTimeoutError as err:
        LOG.warning("Connection Refused")
        raise ConnectionFailure

    LOG.info("Connection established")
    return client