If redis connection parameters are defined in configuration params a
    session will be created
427978
def initialize(g, app):
    

    if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:

        # Initialize connections for console commands
        for k, v in app.config['DATABASES']['REDIS'].items():
            init_db_conn(k, **v)

        @app.before_request
        def before_request():
            """
            Assign redis connection pool to the global
            flask object at the beginning of every request
            """
            for k, v in app.config['DATABASES']['REDIS'].items():
                init_db_conn(k, **v)
            g.redis_pool = redis_pool

        if 'test' not in sys.argv:
            @app.teardown_request
            def teardown_request(exception):
                pool = getattr(g, 'redis_pool', None)
                if pool is not None:
                    pool.close()
564918
def _initialize(self):
        
        self._key_prefix = self._config.get('redis', 'key_prefix')
        self._job_expire_interval = int(
            self._config.get('sharq', 'job_expire_interval')
        )
        self._default_job_requeue_limit = int(
            self._config.get('sharq', 'default_job_requeue_limit')
        )

        # initalize redis
        redis_connection_type = self._config.get('redis', 'conn_type')
        db = self._config.get('redis', 'db')
        if redis_connection_type == 'unix_sock':
            self._r = redis.StrictRedis(
                db=db,
                unix_socket_path=self._config.get('redis', 'unix_socket_path')
            )
        elif redis_connection_type == 'tcp_sock':
            self._r = redis.StrictRedis(
                db=db,
                host=self._config.get('redis', 'host'),
                port=self._config.get('redis', 'port')
            )

        self._load_lua_scripts()
1151930
def initialize(config):
    

    # Determine the client class to use
    if 'redis_client' in config:
        client = utils.find_entrypoint('turnstile.redis_client',
                                       config['redis_client'], required=True)
    else:
        client = redis.StrictRedis

    # Extract relevant connection information from the configuration
    kwargs = {}
    for cfg_var, type_ in REDIS_CONFIGS.items():
        if cfg_var in config:
            kwargs[cfg_var] = type_(config[cfg_var])

    # Make sure we have at a minimum the hostname
    if 'host' not in kwargs and 'unix_socket_path' not in kwargs:
        raise redis.ConnectionError("No host specified for redis database")

    # Look up the connection pool configuration
    cpool_class = None
    cpool = {}
    extra_kwargs = {}
    for key, value in config.items():
        if key.startswith('connection_pool.'):
            _dummy, _sep, varname = key.partition('.')
            if varname == 'connection_class':
                cpool[varname] = utils.find_entrypoint(
                    'turnstile.connection_class', value, required=True)
            elif varname == 'max_connections':
                cpool[varname] = int(value)
            elif varname == 'parser_class':
                cpool[varname] = utils.find_entrypoint(
                    'turnstile.parser_class', value, required=True)
            else:
                cpool[varname] = value
        elif key not in REDIS_CONFIGS and key not in REDIS_EXCLUDES:
            extra_kwargs[key] = value
    if cpool:
        cpool_class = redis.ConnectionPool

    # Use custom connection pool class if requested...
    if 'connection_pool' in config:
        cpool_class = utils.find_entrypoint('turnstile.connection_pool',
                                            config['connection_pool'],
                                            required=True)

    # If we're using a connection pool, we'll need to pass the keyword
    # arguments to that instead of to redis
    if cpool_class:
        cpool.update(kwargs)

        # Use a custom connection class?
        if 'connection_class' not in cpool:
            if 'unix_socket_path' in cpool:
                if 'host' in cpool:
                    del cpool['host']
                if 'port' in cpool:
                    del cpool['port']

                cpool['path'] = cpool['unix_socket_path']
                del cpool['unix_socket_path']

                cpool['connection_class'] = redis.UnixDomainSocketConnection
            else:
                cpool['connection_class'] = redis.Connection

        # Build the connection pool to use and set up to pass it into
        # the redis constructor...
        kwargs = dict(connection_pool=cpool_class(**cpool))

    # Build and return the database
    kwargs.update(extra_kwargs)
    return client(**kwargs)
633009
def init_session(db_url=None, echo=False, engine=None, settings=None):
    
    if engine is None:
        engine = init_engine(db_url=db_url, echo=echo, settings=settings)
    return sessionmaker(bind=engine)
866989
private void saveSession(Session session) throws UnknownSessionException {
		if (session == null || session.getId() == null) {
			logger.error("session or session id is null");
			throw new UnknownSessionException("session or session id is null");
		}
		byte[] key;
		byte[] value;
		try {
			key = keySerializer.serialize(getRedisSessionKey(session.getId()));
			value = valueSerializer.serialize(session);
		} catch (SerializationException e) {
			logger.error("serialize session error. session id=" + session.getId());
			throw new UnknownSessionException(e);
		}
		if (expire == DEFAULT_EXPIRE) {
			this.redisManager.set(key, value, (int) (session.getTimeout() / MILLISECONDS_IN_A_SECOND));
			return;
		}
		if (expire != NO_EXPIRE && expire * MILLISECONDS_IN_A_SECOND < session.getTimeout()) {
			logger.warn("Redis session expire time: "
					+ (expire * MILLISECONDS_IN_A_SECOND)
					+ " is less than Session timeout: "
					+ session.getTimeout()
					+ " . It may cause some problems.");
		}
		this.redisManager.set(key, value, expire);
	}
604978
def get_session_value(self, name, default=None):
        """"""

        value = self.redis().hget(self._session_key, name) or default
        self._update_session_expiration()
        return value
936860
async def _make_connection(self):
        """"""
        return await aioredis.create_redis(
            'redis://{}:{}'.format(
                self._redis_params.get('host', 'localhost'),
                self._redis_params.get('port', 6379)
            ),
            db=int(self._redis_params.get('db', 1))
        )
973372
function initRedis(config, callback) {

  var self = this;

  protos.util.checkLocalPort(config.port, function(err) {

    if (err) {
      app.log("RedisTransport [%s:%s] %s", config.host, config.port, err.code);
    } else {

      // Set redis client
      self.client = redis.createClient(config.port, config.host, self.options);

      // Handle error event
      self.client.on('error', function(err) {
        callback.call(self, err);
      });

      // Authenticate if password provided
      if (typeof config.password == 'string') {
        self.client.auth(config.password, function(err, res) {
          if (err) {
            app.log("RedisTransport: [%s:%s] %s", config.host, config.port, err.code);
          } else if (typeof config.db == 'number' && config.db !== 0) {
            self.client.select(config.db, function(err, res) {
              if (err) callback.call(self, err);
              else callback.call(self, null);
            });
          } else {
            callback.call(self, null);
          }
        });
      } else if (typeof config.db == 'number' && config.db !== 0) {
        self.client.select(config.db, function(err, res) {
          callback.call(self, err);
        });
      } else {
        callback.call(self, null);
      }

    }
  });

}
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
1321926
def _redis_strict_pc(func):
    
    phase = "session_%s" % func.__name__

    @functools.wraps(func)
    def wrapper(self, session, *args, **kwargs):
        try:
            func(self, session, *args, **kwargs)
            self.logger.debug("%s -> %s" % (session.meepo_unique_id, phase))
            return True
        except Exception as e:
            if self.strict:
                raise
            if isinstance(e, redis.ConnectionError):
                self.logger.warn("redis connection error in %s: %s" % (
                    phase, session.meepo_unique_id))
            else:
                self.logger.exception(e)
            return False
    return wrapper
602946
protected function connect()
    {
        if (!is_object(self::$instance)) {
            $func = $this->options['persistent'] ? 'pconnect' : 'connect';

            self::$instance = new \Redis();
            self::$instance->$func($this->options['host'], $this->options['port'], $this->options['timeout']);

            if ('' != $this->options['password']) {
                self::$instance->auth($this->options['password']);
            }
            if (0 != $this->options['select']) {
                self::$instance->select($this->options['select']);
            }
        }
    }
472859
async def create_session(self, **kwargs):
        
        self.opts.update(kwargs)
        self._session = aiohttp.ClientSession(**self.opts, loop=self._loop)
        if self.redis_opts:
            if aioredis:
                self._redis = await aioredis.create_redis(**self.redis_opts,
                                                          loop=self._loop)
            else:
                warnings.warn(no_redis_warning)
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()
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)
1366049
def connect(self, **settings):
        
        # compute a unique key for this settings, for caching. Work on the whole
        # dict without directly using known keys to allow the use of unix socket
        # connection or any other (future ?) way to connect to redis
        if not settings:
            settings = self.connection_settings
        connection_key = ':'.join([str(settings[k]) for k in sorted(settings)])
        if connection_key not in self._connections:
            self._connections[connection_key] = redis.StrictRedis(
                                            decode_responses=True, **settings)
        return self._connections[connection_key]
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
    )
678095
def setup(self, redis_conn=None, host='localhost', port=6379):
        '''
        
        '''
        if redis_conn is None:
            if host is not None and port is not None:
                self.redis_conn = redis.Redis(host=host, port=port)
            else:
                raise Exception("Please specify some form of connection "
                                    "to Redis")
        else:
            self.redis_conn = redis_conn

        self.redis_conn.info()