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


Python redis.ConnectionError方法代码示例

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


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

示例1: init

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def init():
    """
    Initialize key value store that will be used for the event publishing.
    That way the main API takes advantage of Redis pub/sub capabilities to push
    events to the event stream API.
    """
    global socketio

    try:
        publisher_store = redis.StrictRedis(
            host=host, port=port, db=redis_db, decode_responses=True
        )
        publisher_store.get("test")
        socketio = SocketIO(message_queue=redis_url)
    except redis.ConnectionError:
        pass

    return socketio 
开发者ID:cgwire,项目名称:zou,代码行数:20,代码来源:publisher_store.py

示例2: listen

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def listen(self):
        """Relay messages from a redis pubsub to all subscribed clients.

        This is run continuously in a separate greenlet.
        """
        pubsub = redis_conn.pubsub()
        name = self.name
        if isinstance(name, six.text_type):
            name = name.encode("utf-8")
        try:
            pubsub.subscribe([name])
        except ConnectionError:
            app.logger.exception("Could not connect to redis.")
        log("Listening on channel {}".format(self.name))
        for message in pubsub.listen():
            data = message.get("data")
            if message["type"] == "message" and data != "None":
                channel = message["channel"]
                payload = "{}:{}".format(channel.decode("utf-8"), data.decode("utf-8"))
                for client in self.clients:
                    gevent.spawn(client.send, payload)
            gevent.sleep(0.001) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:24,代码来源:sockets.py

示例3: subscribe

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def subscribe(self):
		# Try to subscribe.  If you fail, reconnect and try again.
		# If you fail, allow the resulting exception to be passed on.

		try:
			# Create a pubsub to receive messages
			self.pubsub = self.dataclient.pubsub(ignore_subscribe_messages=True)

			# Subscribe to act_player_info keyspace events
			self.pubsub.psubscribe(u'__key*__:act_player_info')
		except redis.ConnectionError:
			self.connect()

			# Try again to subscribe
			# Create a pubsub to receive messages
			self.pubsub = self.dataclient.pubsub(ignore_subscribe_messages=True)

			# Subscribe to act_player_info keyspace events
			self.pubsub.subscribe(u'__key*__:act_player_info') 
开发者ID:dhrone,项目名称:pydPiper,代码行数:21,代码来源:musicdata_rune.py

示例4: get

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def get(cls, pk, force=False):
        if not force:
            ident_key = identity_key(cls, pk)
            if cls._db_session.identity_map and \
                    ident_key in cls._db_session.identity_map:
                return cls._db_session.identity_map[ident_key]

            try:
                cached_val = cls._cache_client.get(cls.gen_raw_key(pk))
                if cached_val:
                    cls._statsd_incr('hit')
                    return cls.from_cache(cached_val)
            except redis.ConnectionError as e:
                logger.error(e)
            except TypeError as e:
                logger.error(e)

        cls._statsd_incr('miss')

        obj = cls._db_session().query(cls).get(pk)
        if obj is not None:
            cls.set_raw(obj.__rawdata__)
        return obj 
开发者ID:MrKiven,项目名称:ECache,代码行数:25,代码来源:core.py

示例5: wait_serve

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def wait_serve(ip_port, timeout=5):

    t = time.time() + timeout

    rcl = get_client(ip_port)

    while time.time() < t:
        try:
            rcl.hget('foo', 'foo')
            logger.info('redis is ready: ' + repr(ip_port))
            return

        except redis.ConnectionError as e:
            logger.info('can not connect to redis: ' +
                        repr(ip_port) + ' ' + repr(e))
            time.sleep(0.1)
            continue
    else:
        logger.error('can not connect to redis: ' + repr(ip_port))
        raise 
开发者ID:bsc-s2,项目名称:pykit,代码行数:22,代码来源:redisutil.py

示例6: __init__

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def __init__(self, logger=None, destination=None, *args, **kwargs):
        import redis
        super(RedisQueue, self).__init__(*args, **kwargs)
        host = os.environ.get('ZTAG_REDIS_HOST', 'localhost')
        port = int(os.environ.get('ZTAG_REDIS_PORT', 6379))
        if destination == "full_ipv4":
            queue = "ipv4"
        elif destination == "alexa_top1mil":
            queue = "domain"
        else:
            raise Exception("invalid destination: %s" % destination)
        self.logger = logger
        self.queue = queue
        try:
            self.redis = redis.Redis(host=host, port=port, db=0,
                                     socket_connect_timeout=10)
        except redis.ConnectionError as e:
            msg = "could not connect to redis: %s" % str(e)
            self.logger.fatal(msg)
        # batching
        self.queued = 0
        self.retries = 0
        self.records = []
        self.certificates = [] 
开发者ID:zmap,项目名称:ztag,代码行数:26,代码来源:stream.py

示例7: push

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def push(self, noretry=False):
        import redis
        if self.queued == 0:
            return
        try:
            p = self.redis.pipeline()
            for r in self.records:
                p.rpush(self.queue, r)
            for r in self.certificates:
                p.rpush(self.CERTIFICATES_QUEUE, r)
            p.execute()
            self.queued = 0
            self.records = []
            self.certificates = []
            self.retries = 0
        except redis.ConnectionError as e:
            time.sleep(1.0)
            self.retries += 1
            if self.retries > self.MAX_RETRIES or noretry:
                msg = "redis connection error: %s" % str(e)
                self.logger.fatal(msg)
                self.redis = None 
开发者ID:zmap,项目名称:ztag,代码行数:24,代码来源:stream.py

示例8: set_redis

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def set_redis(self, redis_url: str, redis_timeout: int = 10) -> None:
        """ Realiza a autenticação no servidor Redis utilizando a URL informada.

        Args:
            redis_url (str): URL para conectar ao servidor Redis, exemplo: redis://user:password@localhost:6379/2.
            redis_timeout (int): O timeout padrão (em segundos).

        Raises:
            cartolafc.CartolaFCError: Se não for possível se conectar ao servidor Redis
        """
        if not redis_url:
            return

        self._redis_url = redis_url
        self._redis_timeout = redis_timeout if isinstance(redis_timeout, int) and redis_timeout > 0 else 10

        try:
            self._redis = redis.StrictRedis.from_url(url=redis_url)
            self._redis.ping()
        except (ConnectionError, TimeoutError, ValueError):
            self._redis = None
            raise CartolaFCError('Erro conectando ao servidor Redis.') 
开发者ID:vicenteneto,项目名称:python-cartolafc,代码行数:24,代码来源:api.py

示例9: redis

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def redis(self, db=0):
        # The decode_responses flag here directs the client to convert the responses from Redis into Python strings
        # using the default encoding utf-8.  This is client specific.
        function = f"{__name__}.{sys._getframe().f_code.co_name}"
        try:
            red = redis.StrictRedis(host=self.host, port=self.port, db=self.db, encoding="utf-8", decode_responses=True)
            red.set("test", 0)
        except redis.ConnectionError:
            log_data = {
                "function": function,
                "message": "Redis Connection error",
                "host": self.host,
                "port": self.port
            }
            current_app.logger.error(log_data)
            sentry.captureException()
        return red 
开发者ID:Netflix,项目名称:lemur,代码行数:19,代码来源:redis.py

示例10: remove_proxy

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def remove_proxy(self):
        """
        移除代理
        :return: None
        """
        logger.info(f'Removing {CLIENT_NAME}...')
        try:
            # 由于拨号就会中断连接,所以每次都要重新建立连接
            if hasattr(self, 'redis') and self.redis:
                self.redis.close()
            self.redis = RedisClient()
            self.redis.remove(CLIENT_NAME)
            logger.info(f'Removed {CLIENT_NAME} successfully')
            return True
        except redis.ConnectionError:
            logger.info(f'Remove {CLIENT_NAME} failed') 
开发者ID:Python3WebSpider,项目名称:AdslProxy,代码行数:18,代码来源:sender.py

示例11: test_failed_redis_connection

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def test_failed_redis_connection(self, monkeypatch):
        """redis not available"""
        def raise_exception():
            raise redis.ConnectionError()

        monkeypatch.setattr(app, "AsyncResult", lambda task_id: raise_exception())

        url = reverse(self.URL_NAME, kwargs={"task_id": "mock_task_id"})
        request = RequestFactory().get(url)
        request.META["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"  # AJAX request
        request.user = User.objects.create(username="testuser", is_superuser=False, is_staff=False)

        response = views.task_status_ajax(request, "mock_task_id")

        assert response.status_code == 200, "Should be callable"
        assert json.loads(response.content.decode()) == {
            "state": "failed",
            "error_message": "A server process (redis) is not running, please contact the administrator"
        } 
开发者ID:hoelsner,项目名称:product-database,代码行数:21,代码来源:test_django_project_views.py

示例12: _setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def _setup():
    '''Initialize the module
    This adds a set of global variables
    '''
    global parser, args, config, r, response, patch

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--inifile", default=os.path.join(path, name + '.ini'), help="name of the configuration file")
    args = parser.parse_args()

    config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
    config.read(args.inifile)

    try:
        r = redis.StrictRedis(host=config.get('redis', 'hostname'), port=config.getint('redis', 'port'), db=0, charset='utf-8', decode_responses=True)
        response = r.client_list()
    except redis.ConnectionError:
        raise RuntimeError("cannot connect to Redis server")

    # combine the patching from the configuration file and Redis
    patch = EEGsynth.patch(config, r)

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print('LOCALS: ' + ', '.join(locals().keys())) 
开发者ID:eegsynth,项目名称:eegsynth,代码行数:27,代码来源:postprocessing.py

示例13: _setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def _setup():
    '''Initialize the module
    This adds a set of global variables
    '''
    global parser, args, config, r, response, patch

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--inifile", default=os.path.join(path, name + '.ini'), help="name of the configuration file")
    args = parser.parse_args()

    config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
    config.read(args.inifile)

    try:
        r = redis.StrictRedis(host=config.get('redis', 'hostname'), port=config.getint('redis', 'port'), db=0, charset='utf-8', decode_responses=True)
    except redis.ConnectionError:
        raise RuntimeError("cannot connect to Redis server")

    # combine the patching from the configuration file and Redis
    patch = EEGsynth.patch(config, r)

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print('LOCALS: ' + ', '.join(locals().keys())) 
开发者ID:eegsynth,项目名称:eegsynth,代码行数:26,代码来源:outputcvgate.py

示例14: _setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def _setup():
    """Initialize the module
    This adds a set of global variables
    """
    global parser, args, config, r, response, patch

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--inifile", default=os.path.join(path, name + '.ini'), help="name of the configuration file")
    args = parser.parse_args()

    config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
    config.read(args.inifile)

    try:
        r = redis.StrictRedis(host=config.get('redis', 'hostname'), port=config.getint('redis', 'port'), db=0, charset='utf-8', decode_responses=True)
        response = r.client_list()
    except redis.ConnectionError:
        raise RuntimeError("cannot connect to Redis server")

    # combine the patching from the configuration file and Redis
    patch = EEGsynth.patch(config, r)

    # there should not be any local variables in this function, they should all be global
    if len(locals()):
        print("LOCALS: " + ", ".join(locals().keys())) 
开发者ID:eegsynth,项目名称:eegsynth,代码行数:27,代码来源:endorphines.py

示例15: _setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import ConnectionError [as 别名]
def _setup():
    '''Initialize the module
    This adds a set of global variables
    '''
    global parser, args, config, r, response, patch

    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--inifile", default=os.path.join(path, name + '.ini'), help="name of the configuration file")
    args = parser.parse_args()

    config = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
    config.read(args.inifile)

    try:
        r = redis.StrictRedis(host=config.get('redis', 'hostname'), port=config.getint('redis', 'port'), db=0, charset='utf-8', decode_responses=True)
        response = r.client_list()
    except redis.ConnectionError:
        raise RuntimeError("cannot connect to Redis server")

    # combine the patching from the configuration file and Redis
    patch = EEGsynth.patch(config, r) 
开发者ID:eegsynth,项目名称:eegsynth,代码行数:23,代码来源:plotcontrol.py


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