Return a StrictRedis instance or None based on redis_spec.

        redis_spec may be None, a Redis URL, or a StrictRedis instance
327867
def _init_redis(redis_spec):
        
        if not redis_spec:
            return
        if isinstance(redis_spec, six.string_types):
            return redis.StrictRedis.from_url(redis_spec)
        # assume any other value is a valid instance
        return redis_spec
745752
async def _create_redis_pool(*args, **kwargs):
        

        if StrictVersion(aioredis.__version__) >= StrictVersion('1.0.0'):  # pragma no cover
            return await aioredis.create_redis_pool(*args, **kwargs)
        else:  # pragma no cover
            return await aioredis.create_pool(*args, **kwargs)
1240877
def create_redis_client(self):
        """"""
        return ray.services.create_redis_client(
            self._redis_address, self._ray_params.redis_password)
969338
def get(self, name, strict=True):
        """"""
        if not isinstance(name, str) or name.startswith('_'):
            raise AttributeError(self.__class__.__name__, name)
        elif strict and name not in self._possible_attributes:
            raise AttributeError('%s is not a valid attribute of %r.' %
                                 (name, self))
        elif name in self._attributes:
            return self._attributes[name]
        else:
            raise exceptions.AttributeNotProvided(name)
1085354
def get_redis_connection(config, use_strict_redis=False):
    
    redis_cls = redis.StrictRedis if use_strict_redis else redis.Redis

    if 'URL' in config:
        return redis_cls.from_url(config['URL'], db=config.get('DB'))

    if 'USE_REDIS_CACHE' in config.keys():

        try:
            # Assume that we're using django-redis
            from django_redis import get_redis_connection as get_redis
            return get_redis(config['USE_REDIS_CACHE'])
        except ImportError:
            pass

        from django.core.cache import caches
        cache = caches[config['USE_REDIS_CACHE']]
        # We're using django-redis-cache
        try:
            return cache._client
        except AttributeError:
            # For django-redis-cache > 0.13.1
            return cache.get_master_client()

    if 'UNIX_SOCKET_PATH' in config:
        return redis_cls(unix_socket_path=config['UNIX_SOCKET_PATH'], db=config['DB'])

    if 'SENTINELS' in config:
        sentinel_kwargs = {
            'db': config.get('DB'),
            'password': config.get('PASSWORD'),
            'socket_timeout': config.get('SOCKET_TIMEOUT'),
        }
        sentinel_kwargs.update(config.get('CONNECTION_KWARGS', {}))
        sentinel = Sentinel(config['SENTINELS'], **sentinel_kwargs)
        return sentinel.master_for(
            service_name=config['MASTER_NAME'], redis_class=redis_cls,
        )

    return redis_cls(host=config['HOST'], port=config['PORT'], db=config['DB'], password=config.get('PASSWORD'), ssl=config.get('SSL', False))
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)
1233137
def reconnect_redis(self):
        '''
        '''

        if self.shared_client and Storage.storage:
            return Storage.storage

        storage = Redis(
            port=self.context.config.REDIS_RESULT_STORAGE_SERVER_PORT,
            host=self.context.config.REDIS_RESULT_STORAGE_SERVER_HOST,
            db=self.context.config.REDIS_RESULT_STORAGE_SERVER_DB,
            password=self.context.config.REDIS_RESULT_STORAGE_SERVER_PASSWORD
        )

        if self.shared_client:
            Storage.storage = storage
        return storage
1177217
def shared_options(rq):
    ""
    return {
        'url': rq.redis_url,
        'config': None,
        'worker_class': rq.worker_class,
        'job_class': rq.job_class,
        'queue_class': rq.queue_class,
        'connection_class': rq.connection_class,
    }
46932
def one_instance(function=None, key='', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
    
    def _dec(run_func):
        def _caller(*args, **kwargs):
            ret_value = None
            have_lock = False
            # Use Redis AOF for persistent lock.
            if REDIS_CLIENT.config_get('appendonly').values()[0] == 'no':
                REDIS_CLIENT.config_set('appendonly', 'yes')
            lock = REDIS_CLIENT.lock(key, timeout=timeout)
            try:
                logger.debug(
                    '%s: trying to acquire lock (PID %d).'
                    % (key, os.getpid()))
                have_lock = lock.acquire(blocking=False)
                if have_lock:
                    logger.debug(
                        '%s: acquired lock (PID %d).' % (key, os.getpid()))
                    ret_value = run_func(*args, **kwargs)
                else:
                    logger.error(
                        '%s: did not acquire lock (PID %d).'
                        % (key, os.getpid()))
            finally:
                if have_lock:
                    lock.release()
                    logger.debug(
                        '%s: released lock (PID %d).' % (key, os.getpid()))
            return ret_value
        return _caller
    return _dec(function) if function is not None else _dec
192121
def get_spec(name, http_client=None, config=None):
    
    http_client = http_client or requests_client.RequestsClient()

    def load_spec():
        loader = Loader(http_client)
        return loader.load_spec(build_spec_url(name))

    spec_dict = cache.get_or_set(build_cache_name(name), load_spec, app_settings.ESI_SPEC_CACHE_DURATION)
    config = dict(CONFIG_DEFAULTS, **(config or {}))
    return Spec.from_dict(spec_dict, build_spec_url(name), http_client, config)
63006
def get_connection(self, internal=False):
        
        # Determine the connection string to use.
        connect_string = self.connect_string
        if internal:
            connect_string = self.internal_connect_string

        # Stripe Redis protocol prefix coming from the API.
        connect_string = connect_string.strip('redis://')
        host, port = connect_string.split(':')

        # Build and return the redis client.
        return redis.StrictRedis(host=host, port=port, password=self._password)
681498
def _redis_client(opts):
    '''
    
    '''
    redis_host = opts.get("eauth_redis_host", "localhost")
    redis_port = opts.get("eauth_redis_port", 6379)
    try:
        return rediscluster.StrictRedisCluster(host=redis_host, port=redis_port, decode_responses=True)
    except rediscluster.exceptions.RedisClusterException as err:
        log.warning(
            'Failed to connect to redis at %s:%s - %s',
            redis_host, redis_port, err
        )
        return None
1118449
def resource_spec(opts):
    
    resources = _load(opts.resources, opts.output_dir)
    if opts.resource_name not in resources:
        sys.stderr.write('Invalid resource name: {}\n'.format(opts.resource_name))
        return 1
    print(resources[opts.resource_name].spec)
717870
public IRedisClient getRedisClient(String host, int port, String username, String password) {
        return getRedisClient(host, port, username, password, null);
    }
1103155
def parse(url):
    """"""
    config = {}

    url = urlparse.urlparse(url)
    # Handle python 2.6 broken url parsing
    path, query = url.path, url.query
    if '?' in path and query == '':
        path, query = path.split('?', 1)

    cache_args = dict([(key.upper(), ';'.join(val)) for key, val in
                       urlparse.parse_qs(query).items()])

    # Update with environment configuration.
    backend = BACKENDS.get(url.scheme)
    if not backend:
        raise Exception('Unknown backend: "{0}"'.format(url.scheme))

    config['BACKEND'] = BACKENDS[url.scheme]

    redis_options = {}
    if url.scheme == 'hiredis':
        redis_options['PARSER_CLASS'] = 'redis.connection.HiredisParser'

    # File based
    if not url.netloc:
        if url.scheme in ('memcached', 'pymemcached', 'djangopylibmc'):
            config['LOCATION'] = 'unix:' + path

        elif url.scheme in ('redis', 'hiredis'):
            match = re.match(r'.+?(?P<db>\d+)', path)
            if match:
                db = match.group('db')
                path = path[:path.rfind('/')]
            else:
                db = '0'
            config['LOCATION'] = 'unix:%s:%s' % (path, db)
        else:
            config['LOCATION'] = path
    # URL based
    else:
        # Handle multiple hosts
        config['LOCATION'] = ';'.join(url.netloc.split(','))

        if url.scheme in ('redis', 'hiredis'):
            if url.password:
                redis_options['PASSWORD'] = url.password
            # Specifying the database is optional, use db 0 if not specified.
            db = path[1:] or '0'
            port = url.port if url.port else 6379
            config['LOCATION'] = "redis://%s:%s/%s" % (url.hostname, port, db)

    if redis_options:
        config.setdefault('OPTIONS', {}).update(redis_options)

    if url.scheme == 'uwsgicache':
        config['LOCATION'] = config.get('LOCATION', 'default') or 'default'

    # Pop special options from cache_args
    # https://docs.djangoproject.com/en/1.10/topics/cache/#cache-arguments
    options = {}
    for key in ['MAX_ENTRIES', 'CULL_FREQUENCY']:
        val = cache_args.pop(key, None)
        if val is not None:
            options[key] = int(val)
    if options:
        config.setdefault('OPTIONS', {}).update(options)

    config.update(cache_args)

    return config
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
807406
def _noneload(l: Loader, value, type_) -> None:
    
    if value is None:
        return None
    raise TypedloadValueError('Not None', value=value, type_=type_)