当前位置: 首页>>代码示例>>Python>>正文


Python errors.ServerSelectionTimeoutError方法代码示例

本文整理汇总了Python中pymongo.errors.ServerSelectionTimeoutError方法的典型用法代码示例。如果您正苦于以下问题:Python errors.ServerSelectionTimeoutError方法的具体用法?Python errors.ServerSelectionTimeoutError怎么用?Python errors.ServerSelectionTimeoutError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymongo.errors的用法示例。


在下文中一共展示了errors.ServerSelectionTimeoutError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: select_server_by_address

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def select_server_by_address(self, address,
                                 server_selection_timeout=None):
        """Return a Server for "address", reconnecting if necessary.

        If the server's type is not known, request an immediate check of all
        servers. Time out after "server_selection_timeout" if the server
        cannot be reached.

        :Parameters:
          - `address`: A (host, port) pair.
          - `server_selection_timeout` (optional): maximum seconds to wait.
            If not provided, the default value
            common.SERVER_SELECTION_TIMEOUT is used.

        Calls self.open() if needed.

        Raises exc:`ServerSelectionTimeoutError` after
        `server_selection_timeout` if no matching servers are found.
        """
        return self.select_server(any_server_selector,
                                  server_selection_timeout,
                                  address) 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:24,代码来源:topology.py

示例2: wait_for_ok_and_master

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def wait_for_ok_and_master(module, connection_params, timeout = 180):
    start_time = dtdatetime.now()
    while True:
        try:
            client = MongoClient(**connection_params)
            authenticate(client, connection_params["username"], connection_params["password"])

            status = client.admin.command('replSetGetStatus', check=False)
            if status['ok'] == 1 and status['myState'] == 1:
                return

        except ServerSelectionTimeoutError:
            pass

        client.close()

        if (dtdatetime.now() - start_time).seconds > timeout:
            module.fail_json(msg='reached timeout while waiting for rs.status() to become ok=1')

        time.sleep(1) 
开发者ID:UnderGreen,项目名称:ansible-role-mongodb,代码行数:22,代码来源:mongodb_replication.py

示例3: db_connect

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def db_connect():
    maxSevSelDelay = 1
    try:
        mongo_host = 'localhost'
        mongo_port = 27017

        if 'MONGO_PORT_27017_TCP_ADDR' in os.environ :
            mongo_host = os.environ['MONGO_PORT_27017_TCP_ADDR']

        if 'MONGO_PORT_27017_TCP_PORT' in os.environ:
            mongo_port = int(os.environ['MONGO_PORT_27017_TCP_PORT'])

        client = MongoClient(mongo_host, mongo_port, serverSelectionTimeoutMS=maxSevSelDelay)
        client.server_info()
        return client

    except ServerSelectionTimeoutError as err:
        exit("Failed to connect to MongoDB.") 
开发者ID:flipkart-incubator,项目名称:Astra,代码行数:20,代码来源:dbconnection.py

示例4: setUpClass

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def setUpClass(cls):
        """
        Instantiate the adapter before any tests in the test case run.
        """
        from pymongo.errors import ServerSelectionTimeoutError
        from pymongo import MongoClient

        cls.has_mongo_connection = False

        try:
            client = MongoClient(
                serverSelectionTimeoutMS=0.1
            )
            client.server_info()

            cls.adapter = MongoDatabaseAdapter(
                database_uri='mongodb://localhost:27017/chatterbot_test_database'
            )

            cls.has_mongo_connection = True

        except ServerSelectionTimeoutError:
            pass 
开发者ID:gunthercox,项目名称:ChatterBot,代码行数:25,代码来源:test_mongo_adapter.py

示例5: init_database

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def init_database(self):
        """
        Initializes the database connection to MongoDB.
        Also pre-caches potentially heavy resources from the DB.
        :return:
        """
        self.log.info('Connecting to Database...')
        self.db = Database(self, self.cfg.db)
        try:
            await self.db[self.db.db_nam].collection.find_one({})
            if self.cfg.cache.type not in ['redis', 'mixed']:
                await self.db.precache_settings()
                await self.db.precache_profiles()
                await self.db.precache_resources()
            set_color_cache_coll(self.db[self.db.db_nam].ColorCache)
        except ServerSelectionTimeoutError:
            self.log.error('A Connection To The Database Host Failed!')
            exit(errno.ETIMEDOUT)
        except OperationFailure:
            self.log.error('Database Access Operation Failed!')
            exit(errno.EACCES)
        self.log.info('Successfully Connected to Database') 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:24,代码来源:sigma.py

示例6: gather_configured_members_ips

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def gather_configured_members_ips(mongo_tasks_ips, mongo_port):
    current_ips = set()
    logger = logging.getLogger(__name__)
    for t in mongo_tasks_ips:
        mc = pm.MongoClient(t, mongo_port)
        try:
            config = mc.admin.command("replSetGetConfig")['config']
            for m in config['members']:
                current_ips.add(m['host'].split(":")[0])
            # Let's accept the first configuration found. Read as room for improvement!
            break
        except ServerSelectionTimeoutError as ssete:
            logger.debug("cannot connect to {} to get configuration, failed ({})".format(t,ssete))
        except OperationFailure as of:
            logger.debug("no configuration found in node {} ({})".format(t,of))
        finally:
            mc.close()
    logger.debug("Current members in mongo configurations: {}".format(current_ips))
    return current_ips 
开发者ID:smartsdk,项目名称:mongo-rs-controller-swarm,代码行数:21,代码来源:replica_ctrl.py

示例7: get_primary_ip

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def get_primary_ip(tasks_ips, mongo_port):
    logger = logging.getLogger(__name__)

    primary_ips = []
    for t in tasks_ips:
        mc = pm.MongoClient(t, mongo_port)
        try:
            if mc.is_primary:
                primary_ips.append(t)
        except ServerSelectionTimeoutError as ssete:
            logger.debug("cannot connect to {} check if primary, failed ({})".format(t,ssete))
        except OperationFailure as of:
            logger.debug("no configuration found in node {} ({})".format(t,of))
        finally:
            mc.close()

    if len(primary_ips) > 1:
        logger.warning("Multiple primaries were found ({}). Let's use the first.".format(primary_ips))

    if primary_ips:
        logger.info("Primary is: {}".format(primary_ips[0]))
        return primary_ips[0] 
开发者ID:smartsdk,项目名称:mongo-rs-controller-swarm,代码行数:24,代码来源:replica_ctrl.py

示例8: test_ServerSelectionTimeoutError_no_retry

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def test_ServerSelectionTimeoutError_no_retry():
    error = ServerSelectionTimeoutError('some error')
    with patch('arctic.decorators._log_exception', autospec=True) as le:
        @mongo_retry
        def foo():
            raise error
        with pytest.raises(ServerSelectionTimeoutError) as e:
            foo()
    assert 'some error' in str(e.value)
    assert le.call_count == 1 
开发者ID:man-group,项目名称:arctic,代码行数:12,代码来源:test_decorators_unit.py

示例9: select_servers

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def select_servers(self,
                       selector,
                       server_selection_timeout=None,
                       address=None):
        """Return a list of Servers matching selector, or time out.

        :Parameters:
          - `selector`: function that takes a list of Servers and returns
            a subset of them.
          - `server_selection_timeout` (optional): maximum seconds to wait.
            If not provided, the default value common.SERVER_SELECTION_TIMEOUT
            is used.
          - `address`: optional server address to select.

        Calls self.open() if needed.

        Raises exc:`ServerSelectionTimeoutError` after
        `server_selection_timeout` if no matching servers are found.
        """
        if server_selection_timeout is None:
            server_timeout = self._settings.server_selection_timeout
        else:
            server_timeout = server_selection_timeout

        with self._lock:
            server_descriptions = self._select_servers_loop(
                selector, server_timeout, address)

            return [self.get_server_by_address(sd.address)
                    for sd in server_descriptions] 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:32,代码来源:topology.py

示例10: _select_servers_loop

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def _select_servers_loop(self, selector, timeout, address):
        """select_servers() guts. Hold the lock when calling this."""
        now = _time()
        end_time = now + timeout
        server_descriptions = self._description.apply_selector(
            selector, address)

        while not server_descriptions:
            # No suitable servers.
            if timeout == 0 or now > end_time:
                raise ServerSelectionTimeoutError(
                    self._error_message(selector))

            self._ensure_opened()
            self._request_check_all()

            # Release the lock and wait for the topology description to
            # change, or for a timeout. We won't miss any changes that
            # came after our most recent apply_selector call, since we've
            # held the lock until now.
            self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
            self._description.check_compatible()
            now = _time()
            server_descriptions = self._description.apply_selector(
                selector, address)

        self._description.check_compatible()
        return server_descriptions 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:30,代码来源:topology.py

示例11: connect

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def connect(self):
        try:
            logging.debug("Getting MongoDB connection to %s (replicaSet=%s, readPreference=%s, readPreferenceTags=%s, ssl=%s)" % (
                self.uri,
                self.replset,
                self.read_pref,
                self.do_rp_tags,
                self.do_ssl(),
            ))
            conn = MongoClient(**self.client_opts())
            if self.do_connect:
                conn['admin'].command({"ping": 1})
        except (ConfigurationError, ConnectionFailure, OperationFailure, ServerSelectionTimeoutError), e:
            logging.error("Unable to connect to %s! Error: %s" % (self.uri, e))
            raise DBConnectionError(e) 
开发者ID:Percona-Lab,项目名称:mongodb_consistent_backup,代码行数:17,代码来源:DB.py

示例12: is_connected

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def is_connected(self):
        try:
            self.client.server_info()
        except ServerSelectionTimeoutError:
            return False
        return True 
开发者ID:clarketm,项目名称:s3recon,代码行数:8,代码来源:mongodb.py

示例13: create_mongo_connection

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def create_mongo_connection(self, hostname="localhost"):
        """
            Creates a connection to YETI's MongoDB.
        :param hostname: Hostname to connect to. Default is "localhost"
        :return: None
        """

        try:
            # Try connecting to MongoDB for 10ms
            self.mongo_client = MongoClient('mongodb://{}:27017/'.format(hostname), serverSelectionTimeoutMS=10)
            self.mongo_client.server_info()
        except errors.ServerSelectionTimeoutError as mongo_conn_err:
            logger.exception(("MongoDB connection issue occurred. "
                              "Error message: " + str(mongo_conn_err)))
            sys.exit(1) 
开发者ID:yeti-platform,项目名称:yeti,代码行数:17,代码来源:yeti_to_elasticsearch.py

示例14: setUp

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def setUp(self):
        self.db_name = 'test_mongo_storage'
        connection_string = 'mongodb://127.0.0.1:27017/?serverSelectionTimeoutMS=100'
        try:
            self.client = Mongo(connection_string, db_name=self.db_name,
                                collection='test')
            list(self.client.get_all({}))
        except ServerSelectionTimeoutError as e:
            raise SkipTest(str(e)) 
开发者ID:djudman,项目名称:evernote-telegram-bot,代码行数:11,代码来源:test_mongo.py

示例15: _select_servers_loop

# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ServerSelectionTimeoutError [as 别名]
def _select_servers_loop(self, selector, timeout, address):
        """select_servers() guts. Hold the lock when calling this."""
        now = _time()
        end_time = now + timeout
        server_descriptions = self._description.apply_selector(
            selector, address, custom_selector=self._settings.server_selector)

        while not server_descriptions:
            # No suitable servers.
            if timeout == 0 or now > end_time:
                raise ServerSelectionTimeoutError(
                    self._error_message(selector))

            self._ensure_opened()
            self._request_check_all()

            # Release the lock and wait for the topology description to
            # change, or for a timeout. We won't miss any changes that
            # came after our most recent apply_selector call, since we've
            # held the lock until now.
            self._condition.wait(common.MIN_HEARTBEAT_INTERVAL)
            self._description.check_compatible()
            now = _time()
            server_descriptions = self._description.apply_selector(
                selector, address,
                custom_selector=self._settings.server_selector)

        self._description.check_compatible()
        return server_descriptions 
开发者ID:wistbean,项目名称:learn_python3_spider,代码行数:31,代码来源:topology.py


注:本文中的pymongo.errors.ServerSelectionTimeoutError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。