當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。