Originally lifted from redis-rb
489199
def _floatify(str, increment = true)
      if (( inf = str.to_s.match(/^([+-])?inf/i) ))
        (inf[1] == "-" ? -1.0 : 1.0) / 0.0
      elsif (( number = str.to_s.match(/^\((\d+)/i) ))
        number[1].to_i + (increment ? 1 : -1)
      else
        Float str.to_s
      end
    rescue ArgumentError
      raise Redis::CommandError, "ERR value is not a valid float"
    end
622760
def method_missing(method, *args, &block)
      fail(Raidis::ConnectionError, 'No Redis backend found.') unless redis

      reloading_connection do
        observing_connection { redis.send(method, *args, &block) }
      end
    end
801044
def redis(self):
        
        redis_url = current_app.config.get("SSE_REDIS_URL")
        if not redis_url:
            redis_url = current_app.config.get("REDIS_URL")
        if not redis_url:
            raise KeyError("Must set a redis connection URL in app config.")
        return StrictRedis.from_url(redis_url)
195357
def _get_redis_server(opts=None):
    '''
    
    '''
    global REDIS_SERVER
    if REDIS_SERVER:
        return REDIS_SERVER
    if not opts:
        opts = _get_redis_cache_opts()

    if opts['cluster_mode']:
        REDIS_SERVER = StrictRedisCluster(startup_nodes=opts['startup_nodes'],
                                          skip_full_coverage_check=opts['skip_full_coverage_check'])
    else:
        REDIS_SERVER = redis.StrictRedis(opts['host'],
                                   opts['port'],
                                   unix_socket_path=opts['unix_socket_path'],
                                   db=opts['db'],
                                   password=opts['password'])
    return REDIS_SERVER
832731
def _get_redis_connection():
    
    url = current_app.config.get('REDIS_URL', 'redis://localhost:6379')
    return redis.from_url(url, decode_responses=True)
1351137
def restore(self, name, value, pttl=0):
        
        with self.pipe as pipe:
            res = pipe.restore(self.redis_key(name), ttl=pttl, value=value)
            f = Future()

            def cb():
                f.set(self.valueparse.decode(res.result))

            pipe.on_execute(cb)
            return f
707425
def get_redis_info():
    """"""
    from kombu.utils.url import _parse_url as parse_redis_url
    from redis import (
        StrictRedis,
        ConnectionError as RedisConnectionError,
        ResponseError as RedisResponseError,
    )
    for conf_name in ('REDIS_URL', 'BROKER_URL', 'CELERY_BROKER_URL'):
        if hasattr(settings, conf_name):
            url = getattr(settings, conf_name)
            if url.startswith('redis://'):
                break
    else:
        log.error("No redis connection info found in settings.")
        return {"status": NO_CONFIG}
    _, host, port, _, password, database, _ = parse_redis_url(url)

    start = datetime.now()
    try:
        rdb = StrictRedis(
            host=host, port=port, db=database,
            password=password, socket_timeout=TIMEOUT_SECONDS,
        )
        info = rdb.info()
    except (RedisConnectionError, TypeError) as ex:
        log.error("Error making Redis connection: %s", ex.args)
        return {"status": DOWN}
    except RedisResponseError as ex:
        log.error("Bad Redis response: %s", ex.args)
        return {"status": DOWN, "message": "auth error"}
    micro = (datetime.now() - start).microseconds
    del rdb  # the redis package does not support Redis's QUIT.
    ret = {
        "status": UP, "response_microseconds": micro,
    }
    fields = ("uptime_in_seconds", "used_memory", "used_memory_peak")
    ret.update({x: info[x] for x in fields})
    return ret
608282
async def create_redis(address, *, db=None, password=None, ssl=None,
                       encoding=None, commands_factory=Redis,
                       parser=None, timeout=None,
                       connection_cls=None, loop=None):
    
    conn = await create_connection(address, db=db,
                                   password=password,
                                   ssl=ssl,
                                   encoding=encoding,
                                   parser=parser,
                                   timeout=timeout,
                                   connection_cls=connection_cls,
                                   loop=loop)
    return commands_factory(conn)
341474
def passed
      v = RRRSpec.redis.hget(key, 'passed')
      v.present? ? v.to_i : nil
    end
654550
def revrank v
      ret = redis.zrevrank rediskey, to_redis(v)
      ret.nil? ? nil : ret.to_i
    end
309306
def validate(self, value, redis):
        '''
        
        '''
        # cleanup
        if type(value) == str:
            value = value.strip()

        value = self.value_or_default(value)

        # validation
        self.validate_required(value)

        if self.regex and not re.match(self.regex, value, flags=re.ASCII):
            raise InvalidFieldError(self.name)

        if self.forbidden and value in self.forbidden:
            raise ReservedFieldError(self.name)

        if self.allowed and value not in self.allowed:
            raise InvalidFieldError(self.name)

        if self.index:
            key = self.key()

            old = debyte_string(redis.hget(key, value))
            old_value = getattr(self.obj, self.name)

            if old is not None and old != self.obj.id:
                raise NotUniqueFieldError(self.name)
            elif old_value != value:
                self.obj._old[self.name] = old_value

        return value
51113
def purge_old(self):
        '''
        
        '''
        if self.keep_max is not None:
            keys = self.redis_conn.keys(self.get_key() + ':*')
            keys.sort(reverse=True)
            while len(keys) > self.keep_max:
                key = keys.pop()
                self.redis_conn.delete(key)
193186
def _final_redis_call(self, final_set, sort_options):
        

        conn = self.cls.get_connection()
        if sort_options is not None:
            # a sort, or values, call the SORT command on the set
            return conn.sort(final_set, **sort_options)
        else:
            # no sort, nor values, simply return the full set
            return conn.smembers(final_set)
1096166
def reconnect
      tries = 0
      begin
        redis.synchronize do |client|
          client.reconnect
        end
      rescue Redis::BaseConnectionError
        if (tries += 1) <= 3
          log "Error reconnecting to Redis; retrying"
          sleep(tries)
          retry
        else
          log "Error reconnecting to Redis; quitting"
          raise
        end
      end
    end
725125
protected function hitRedis()
    {
        $lua = 'local v = redis.call(\'incr\', KEYS[1]) '.
               'if v>1 then return v '.
               'else redis.call(\'setex\', KEYS[1], ARGV[1], 1) return 1 end';

        $this->number = $this->store->connection()->eval($lua, 1, $this->computeRedisKey(), $this->time * 60);

        return $this;
    }
1148885
def remove_redis_keyword(self, keyword):
        '''
        
        '''
        redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword)
        return json.dump({}, self)
1040172
def _get_dicts_from_redis(self, name, index_name, redis_prefix, item):
        
        r = self._redis
        data_dict = {}
        data_index_dict = {}

        if redis_prefix is None:
            raise KeyError ("redis_prefix is missing")

        if r.scard(redis_prefix + index_name + str(item)) > 0:
            data_index_dict[str(item)] = r.smembers(redis_prefix + index_name + str(item))

            for i in data_index_dict[item]:
                json_data = r.get(redis_prefix + name + str(int(i)))
                data_dict[i] = self._deserialize_data(json_data)

            return (data_dict, data_index_dict)

        raise KeyError ("No Data found in Redis for "+ item)