Returns an active Redis client generated from the given database URL.

    Will attempt to extract the database id from the path url fragment, if
    none is provided.
498990
def from_url(url, db=None, **kwargs):
    
    from redis.client import Redis
    return Redis.from_url(url, db, **kwargs)
1207634
def database_caller_creator(self, host, port, name=None):
        '''
        '''

        name = name or 0
        client = redis.StrictRedis(host=host, port=port, db=name)
        pipe = client.pipeline(transaction=False)
        return client, pipe
315497
def create_connection():
    """"""

    global _cached_connection
    settings = oz.settings

    if settings["redis_cache_connections"] and _cached_connection != None:
        return _cached_connection
    else:
        conn = redis.StrictRedis(
            host=settings["redis_host"],
            port=settings["redis_port"],
            db=settings["redis_db"],
            password=settings["redis_password"],
            decode_responses=settings["redis_decode_responses"],
            ssl=settings["redis_use_ssl"],
            ssl_keyfile=settings["redis_ssl_keyfile"],
            ssl_certfile=settings["redis_ssl_certfile"],
            ssl_cert_reqs=settings["redis_ssl_cert_reqs"],
            ssl_ca_certs=settings["redis_ssl_ca_certs"]
        )

        if settings["redis_cache_connections"]:
            _cached_connection = conn

        return conn
44391
def parse_client_table(redis_client):
    
    NIL_CLIENT_ID = ray.ObjectID.nil().binary()
    message = redis_client.execute_command("RAY.TABLE_LOOKUP",
                                           ray.gcs_utils.TablePrefix.CLIENT,
                                           "", NIL_CLIENT_ID)

    # Handle the case where no clients are returned. This should only
    # occur potentially immediately after the cluster is started.
    if message is None:
        return []

    node_info = {}
    gcs_entry = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(message, 0)

    ordered_client_ids = []

    # Since GCS entries are append-only, we override so that
    # only the latest entries are kept.
    for i in range(gcs_entry.EntriesLength()):
        client = (ray.gcs_utils.ClientTableData.GetRootAsClientTableData(
            gcs_entry.Entries(i), 0))

        resources = {
            decode(client.ResourcesTotalLabel(i)):
            client.ResourcesTotalCapacity(i)
            for i in range(client.ResourcesTotalLabelLength())
        }
        client_id = ray.utils.binary_to_hex(client.ClientId())

        # If this client is being removed, then it must
        # have previously been inserted, and
        # it cannot have previously been removed.
        if not client.IsInsertion():
            assert client_id in node_info, "Client removed not found!"
            assert node_info[client_id]["IsInsertion"], (
                "Unexpected duplicate removal of client.")
        else:
            ordered_client_ids.append(client_id)

        node_info[client_id] = {
            "ClientID": client_id,
            "IsInsertion": client.IsInsertion(),
            "NodeManagerAddress": decode(
                client.NodeManagerAddress(), allow_none=True),
            "NodeManagerPort": client.NodeManagerPort(),
            "ObjectManagerPort": client.ObjectManagerPort(),
            "ObjectStoreSocketName": decode(
                client.ObjectStoreSocketName(), allow_none=True),
            "RayletSocketName": decode(
                client.RayletSocketName(), allow_none=True),
            "Resources": resources
        }
    # NOTE: We return the list comprehension below instead of simply doing
    # 'list(node_info.values())' in order to have the nodes appear in the order
    # that they joined the cluster. Python dictionaries do not preserve
    # insertion order. We could use an OrderedDict, but then we'd have to be
    # sure to only insert a given node a single time (clients that die appear
    # twice in the GCS log).
    return [node_info[client_id] for client_id in ordered_client_ids]
771425
def redis_info url, password
      begin
        r = Redis.new url: url, password: password
        info = r.info.merge 'dbsize' => r.dbsize
      rescue Exception => e
        STDERR.puts "[ERROR][#{__FILE__}:#{__LINE__}] Failed to get data from Redis - " +
          "#{url.inspect} (using password #{password.inspect}): #{e.message}\n#{e.backtrace.join("\n")}"
        return {}
      end

      begin
        info['maxmemory'] = @options.fetch(:max_memory) { r.config(:get, 'maxmemory')['maxmemory'] }
      rescue Exception
        info['maxmemory'] = info['used_memory_rss']
      end

      r.quit

      {
        'connections'     => info['connected_clients'].to_i,
        'used_memory'     => info['used_memory'].to_f,
        'used_memory_rss' => info['used_memory_rss'].to_f,
        'fragmentation'   => info['mem_fragmentation_ratio'].to_f,
        'expired_keys'    => info['expired_keys'].to_i,
        'evicted_keys'    => info['evicted_keys'].to_i,
        'hits'            => info['keyspace_hits'].to_i,
        'misses'          => info['keyspace_misses'].to_i,
        'keys'            => info['dbsize'].to_i,
        'max_memory'      => info['maxmemory'].to_i,
        'hit_ratio'       => 0
      }.tap {|d| d['hit_ratio'] = d['hits'].to_f / (d['hits']+d['misses']).to_f if d['hits'] > 0 }
    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)
178269
public IRedisClient getRedisClient(final String host, final int port, final String username,
            final String password, final PoolConfig poolConfig) {
        String poolName = calcRedisPoolName(host, port, username, password, poolConfig);

        try {
            JedisClientPool redisClientPool = cacheRedisClientPools.get(poolName,
                    new Callable<JedisClientPool>() {
                        @Override
                        public JedisClientPool call() throws Exception {
                            return createRedisClientPool(host, port, username, password, poolConfig);
                        }
                    });
            return redisClientPool.borrowObject();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        }
    }
1371121
async function getConnection(url, opts = {}) {

    const dbName = opts.databaseName;
    if (!dbName || dbName === '')
        throw boom.badImplementation('jollof-data-arangodb: databaseName config is required', { url, opts })

    const key = url + dbName;

    //Get connection
    let connection;
    if (connPool[key]) {
        connection = connPool[key];
    } else {
        connection = new Database(url)
        connPool[key] = connection;
    }

    //Now ensure database exists
    const dbNames = await connection.listDatabases();
    if (dbNames.indexOf(dbName) > -1) {
        //our db exists. use it.
        connection.useDatabase(dbName)
    } else {
        //our db does not exist. Attempting to create it
        await connection.createDatabase(dbName, [{ username: opts.username, passw: opts.password }])
        connection.useDatabase(dbName)
    }

    return connection;
}
1160925
def db_url(self, var=DEFAULT_DATABASE_ENV, default=NOTSET, engine=None):
        
        return self.db_url_config(self.get_value(var, default=default), engine=engine)
188277
def find_db_instance(self, name, running=True):
        
        found = None
        for i in self.provider.reddwarf_client.instances.list():
            if i.name == name:
                if not running:  # don't care if it's running or not
                    found = i
                if i.status == 'running':
                    found = i
        if found:
            log.info("Found existing db, %s (%s)" % (found.name, found.id))
            return db_to_dict(found)
431612
def BROKER_URL(self):
        """"""

        # also allow specify broker_url
        broker_url = get('BROKER_URL', None)
        if broker_url:
            log.info("Using BROKER_URL setting: {}".format(broker_url))
            return broker_url

        redis_available = self._redis_available()
        broker_type = self.BROKER_TYPE

        if broker_type == 'redis' and not redis_available:
            log.warn("Choosed broker type is redis, but redis not available. \
                    Check redis package, and REDIS_HOST, REDIS_PORT settings")

        if broker_type == 'redis' and redis_available:

            return 'redis://{host}:{port}/{db}'.format(
                    host=self.REDIS_HOST,
                    port=self.REDIS_PORT,
                    db=self.CELERY_REDIS_BROKER_DB)
        elif broker_type == 'rabbitmq':
            return 'amqp://{user}:{passwd}@{host}:{port}/{vhost}'.format(
                    user=self.RABBITMQ_USER,
                    passwd=self.RABBITMQ_PASSWD,
                    host=self.RABBITMQ_HOST,
                    port=self.RABBITMQ_PORT,
                    vhost=self.RABBITMQ_VHOST)
        else:
            return DEFAULT_BROKER_URL
189258
def get_redis_client(self):
        
        host = self.config['host']
        ports = self.config['ports']
        sentinel_ports = self.config['sentinel_ports']
        sentinel_name = self.config['sentinel_name']
        password = self.config['password']
        databases = self.config['databases']

        if not isinstance(ports, list):
            ports = [ports]

        if not isinstance(sentinel_ports, list):
            sentinel_ports = [sentinel_ports]

        if sentinel_ports:
            assert len(sentinel_ports) == len(ports)
        else:
            sentinel_ports = [None for _ in xrange(len(ports))]

        for port, sentinel_port in izip(ports, sentinel_ports):
            for db in xrange(0, int(databases)):
                master = self.get_master(
                    host, port, sentinel_port, sentinel_name
                )
                pool = redis.ConnectionPool(
                    host=master[0], port=int(master[1]),
                    password=password, db=db
                )
                yield redis.Redis(connection_pool=pool), port, db
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))
1051359
def get(cls, id):
        '''  '''

        if not id:
            return None

        redis = cls.get_redis()
        key = '{}:{}:obj'.format(cls.cls_key(), id)

        if not redis.exists(key):
            return None

        obj = cls(id=id)
        obj._persisted = True

        data = debyte_hash(redis.hgetall(key))

        for fieldname, field in obj.proxy:
            value = field.recover(data, redis)

            setattr(
                obj,
                fieldname,
                value
            )

        return obj
1008067
def fake2db_redis_initiator(self, host, port, number_of_rows, name=None, custom=None):
        '''
        '''

        client, pipe = self.database_caller_creator(host, port, name)

        if custom:
            self.custom_db_creator(number_of_rows, pipe, custom)
            client.save()
            sys.exit(0)

        self.data_filler_simple_registration(number_of_rows, pipe)
        self.data_filler_detailed_registration(number_of_rows, pipe)
        self.data_filler_company(number_of_rows, pipe)
        self.data_filler_user_agent(number_of_rows, pipe)
        self.data_filler_customer(number_of_rows, pipe)

        client.save()
523549
def connect(url=None, schema=None, sql_path=None, multiprocessing=False):
    
    if url is None:
        url = os.environ.get("DATABASE_URL")
    return Database(url, schema, sql_path=sql_path, multiprocessing=multiprocessing)
776822
def create_connection():
    """"""
    # REDIS_URL is defined in .env and loaded into the environment by Honcho
    redis_url = os.getenv('REDIS_URL')
    # If it's not defined, use the Redis default
    if not redis_url:
        redis_url = 'redis://localhost:6379'
    urlparse.uses_netloc.append('redis')
    url = urlparse.urlparse(redis_url)
    return redis.StrictRedis(
        host=url.hostname,
        port=url.port,
        db=0,
        password=url.password
    )