当前位置: 首页>>代码示例>>Python>>正文


Python StrictRedis.info方法代码示例

本文整理汇总了Python中redis.StrictRedis.info方法的典型用法代码示例。如果您正苦于以下问题:Python StrictRedis.info方法的具体用法?Python StrictRedis.info怎么用?Python StrictRedis.info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在redis.StrictRedis的用法示例。


在下文中一共展示了StrictRedis.info方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_redis_info

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
def get_redis_info():
    """Check Redis connection."""
    try:
        url = settings.BROKER_URL
        _, host, port, _, password, db, _ = parse_redis_url(url)
    except AttributeError:
        log.error("No valid Redis connection info found in settings.")
        return {"status": NO_CONFIG}

    start = datetime.now()
    try:
        rdb = StrictRedis(
            host=host, port=port, db=db,
            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
开发者ID:dreganism,项目名称:lore,代码行数:32,代码来源:views.py

示例2: rediscli

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
def rediscli(master=True):
    '''get mgmt connection'''
    for hostname in app.config.get('MONACO_HOSTS', ['localhost']):
        try:
            r = StrictRedis(host=hostname, port=app.config['MGMT_PORT'], socket_connect_timeout=1)
            info = r.info()
            if info['role'] == 'master' or not master:
                return r
            else:
                return StrictRedis(host=info['master_host'], port=app.config['MGMT_PORT'], socket_connect_timeout=1)
        except TimeoutError:
            continue
    raise TimeoutError('Timeout connecting to monaco mgmt db')
开发者ID:asimkhaja,项目名称:monaco,代码行数:15,代码来源:__init__.py

示例3: proxy_stats

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
def proxy_stats(twem_id):
    '''
    Returns live aggregates for a given proxy
    '''
    r = rediscli()
    monaco = schema.Monaco()
    monaco.refresh(r)

    if not str(twem_id) in monaco.twem_ids:
        abort(404)
    twem = schema.MonacoTwem(twem_id=twem_id)
    twem.refresh(r)

    aggregate_rps = 0
    aggregate_connections = 0

    if len(twem.servers) == 1:
        dbapp = schema.App(app_id=twem.servers[0])
        dbapp.refresh(r)
        for node_id, _ in dbapp.nodes.iteritems():
            appcli = StrictRedis(monaco.hostnames_by_node_id[node_id], dbapp.port)
            info = appcli.info()
            if 'instantaneous_ops_per_sec' in info:
                aggregate_rps += info['instantaneous_ops_per_sec']
            if 'connected_clients' in info:
                aggregate_connections += info['connected_clients']
    else:
        for app_id in twem.servers:
            dbapp = schema.App(app_id=app_id)
            dbapp.refresh(r)
            appcli = dbapp.get_master_connection(r)
            info = appcli.info()
            if 'instantaneous_ops_per_sec' in info:
                aggregate_rps += info['instantaneous_ops_per_sec']
            if 'connected_clients' in info:
                aggregate_connections += info['connected_clients']

    return jsonify({'total_rps': aggregate_rps, 'total_connections': aggregate_connections})
开发者ID:asimkhaja,项目名称:monaco,代码行数:40,代码来源:api.py

示例4: probe

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
    def probe(self):
        """
        Get information data about commands stats and return Metric objects

        :return: a generator with informations
        :rtype: generator
        """

        try:
            # Connect to redis server
            redis_client = StrictRedis(
                db=self.database_id, host=self.host,
                password=self.password, port=self.port)

            # Get statistics
            self.redis_infos = redis_client.info(section='commandstats')
        except RedisError as error:
            raise CheckError(
                'Error with Redis server connection: {}'.format(str(error)))

        # Manage probe cookie file data
        with Cookie(self.probe_state_file) as state_file:

            # Iterate over all commands stats
            for stat_name, stat_new_values in self.redis_infos.items():

                # Manage file data
                stat_old_values = state_file.get(stat_name)
                if stat_old_values is None:
                    stat_old_values = {'calls': 0, 'usec': 0}
                state_file[stat_name] = stat_new_values

                # Manage reset or restart
                use_new_values = False
                if stat_old_values.get('calls', 0) > stat_new_values['calls']:
                    use_new_values = True

                # Manage metrics
                for metric_name in ['calls', 'usec']:
                    if use_new_values:
                        metric_value = stat_new_values[metric_name]
                    else:
                        metric_value = (stat_new_values[metric_name]
                                        - stat_old_values[metric_name])

                    yield Metric(
                        'db{}_{}.{}'.format(
                            self.database_id, stat_name, metric_name),
                        metric_value,
                        context='default')
开发者ID:Temelio,项目名称:monitoring-lib-python,代码行数:52,代码来源:get_commands_stats.py

示例5: __init__

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
class Repository:

    def __init__(self, host, port):
        self.r = StrictRedis(host=host, port=port)

# store dictionary
#    redis.hmset(hkey, dict_to_store)
# retrieve dictionary
#    redis.hmget(hkey)
# lists
#    redis.lappend(hkey, string)
#    redis.llen

    def get_item(self, key_store, index):
        length = self.r.llen(key_store)
        if length == 0:
            return None
        if index >= length:
            raise Exception('Index out of range.')
        item_json = self.r.lindex(key_store, length - (index + 1))
        item_dict = json.loads(item_json)
        return item_dict

    def append_item(self, key_store, item):
        item_json = json.dumps(item)
        if not self.r.lpush(key_store, item_json):
            raise Exception('Unable to write key_store: [%s]' % item_json)

    def fetch_all(self, key_store):
        q = []
        length = self.r.llen(key_store)
        for i in range(length):
            item_json = self.r.lindex(key_store, length - (i + 1))
            item_dict = json.loads(item_json)
            q.append(item_dict)
        return q

    def set(self, key_store, list):
        self.r.delete(key_store)
        for item_dict in list:
            item_json = json.dumps(item_dict)
            if not self.r.lpush(key_store, item_json):
                raise Exception('Unable to write key_store: [%s]' % item_json)

    def delete(self, key_store):
        self.r.delete(key_store)

    def info(self):
        return self.r.info()
开发者ID:carlomorelli,项目名称:acrewstic,代码行数:51,代码来源:repository.py

示例6: probe

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
    def probe(self):
        """
        Get information data about connections and return Metric objects

        :return: a generator with informations
        :rtype: generator
        """

        try:
            # Connect to redis server
            redis_client = StrictRedis(
                db=self.database_id,
                host=self.host,
                password=self.password,
                port=self.port)

            # Get statistics
            self.redis_infos = redis_client.info(section=self.section_name)
        except RedisError as error:
            raise CheckError(
                'Error with Redis server connection: {}'.format(str(error)))

        # Get metric value, or raise
        metric_value = None
        if self.metric_name == 'hit_rate':
            metric_value = self._get_hit_rate()
        elif self.metric_name in self.redis_infos:
            metric_value = self.redis_infos[self.metric_name]
        else:
            raise CheckError(
                '"{}": Unknown info metric name'.format(self.metric_name))


        # Build and return Metric objects from data if scalar, else raise
        if isinstance(metric_value, int) or isinstance(metric_value, float):
            yield Metric('db{}_{}'.format(self.database_id, self.metric_name),
                         metric_value)
        else:
            raise CheckError(
                '"{}" value is not an integer or float: "{}" !'.format(
                    self.metric_name, metric_value))
开发者ID:Temelio,项目名称:monitoring-lib-python,代码行数:43,代码来源:scalar_info_value.py

示例7: list_nodes_api

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
def list_nodes_api():
    '''
    This provides a RESTful endpoint for listing MonacoNodes
    HEAD: Returns {'node_ids': [node_id, node_id]}, which only queries master mgmt db
    GET: Returns HEAD + {'<node_id>': {NODE INFO DICT}}, which queries redis servers on each node
    '''
    data = {}
    r = rediscli()
    monaco = schema.Monaco()
    monaco.refresh(r)
    data['node_ids'] = monaco.node_ids

    for node_id in data['node_ids']:
        data[node_id] = {}
        data[node_id]['hostname'] = monaco.hostnames_by_node_id[node_id]
        if request.method == 'HEAD':
            continue
        try:
            rtemp = StrictRedis(host=data[node_id]['hostname'], port=app.config['MGMT_PORT'], socket_connect_timeout=1, socket_timeout=0.5)
            info = rtemp.info()
            data[node_id]['role'] = info['role']
            if data[node_id]['role'] == 'slave':
                data[node_id]['role_details'] = {'master': info['master_host']}
            else:
                data[node_id]['role_details'] = {}
                data[node_id]['role_details']['connected_slaves'] = info['connected_slaves']
                for idx in xrange(int(info['connected_slaves'])):
                    data[node_id]['role_details']['slave%d' % idx] = info['slave%d' % idx]
            node = schema.MonacoNode(node_id=node_id)
            node.refresh(r)
            data[node_id]['mem_usage'] = '%sM' % node.app_info(r)['memory']
            data[node_id]['up'] = True
        except Exception:
            data[node_id]['up'] = False
            data[node_id]['role'] = None
            data[node_id]['role_details'] = None
            data[node_id]['mem_usage'] = None
        data[node_id]['net_usage'] = None
    return jsonify(data)
开发者ID:asimkhaja,项目名称:monaco,代码行数:41,代码来源:api.py

示例8: __init__

# 需要导入模块: from redis import StrictRedis [as 别名]
# 或者: from redis.StrictRedis import info [as 别名]
class RespectfulRequester:

    def __init__(self):
        self.redis = StrictRedis(
            host=config["redis"]["host"],
            port=config["redis"]["port"],
            password=config["redis"]["password"],
            db=config["redis"]["database"])

        try:
            self.redis.echo("Testing Connection")
        except ConnectionError:
            raise RequestsRespectfulRedisError("Could not establish a connection to the provided Redis server")

    def __getattr__(self, attr):
        if attr in ["delete", "get", "head", "options", "patch", "post", "put"]:
            return getattr(self, "_requests_proxy_%s" % attr)
        else:
            raise AttributeError()

    @property
    def redis_prefix(self):
        return "RespectfulRequester"

    def request(self, request_func, realms, wait=False):
        if not isinstance(realms, Sequence) or isinstance(realms, basestring):
            realms = [realms]

        for realm in realms:
            if realm not in self.fetch_registered_realms():
                raise RequestsRespectfulError("Realm '%s' hasn't been registered" % realm)

        if wait:
            while True:
                try:
                    return self._perform_request(request_func, realms)
                except RequestsRespectfulRateLimitedError:
                    pass

                time.sleep(1)
        else:
            return self._perform_request(request_func, realms)

    def fetch_registered_realms(self):
        return list(map(lambda k: k.decode("utf-8"), self.redis.smembers("%s:REALMS" % self.redis_prefix)))

    def register_realm(self, realm, max_requests, timespan):
        redis_key = self._realm_redis_key(realm)

        if not self.redis.hexists(redis_key, "max_requests"):
            self.redis.hmset(redis_key, {"max_requests": max_requests, "timespan": timespan})
            self.redis.sadd("%s:REALMS" % self.redis_prefix, realm)

        return True

    def update_realm(self, realm, **kwargs):
        redis_key = self._realm_redis_key(realm)
        updatable_keys = ["max_requests", "timespan"]

        for updatable_key in updatable_keys:
            if updatable_key in kwargs and type(kwargs[updatable_key]) == int:
                self.redis.hset(redis_key, updatable_key, kwargs[updatable_key])

        return True

    def unregister_realm(self, realm):
        self.redis.delete(self._realm_redis_key(realm))
        self.redis.srem("%s:REALMS" % self.redis_prefix, realm)

        request_keys = self.redis.keys("%s:REQUEST:%s:*" % (self.redis_prefix, realm))
        [self.redis.delete(k) for k in request_keys]

        return True

    def realm_max_requests(self, realm):
        realm_info = self._fetch_realm_info(realm)
        return int(realm_info["max_requests".encode("utf-8")].decode("utf-8"))

    def realm_timespan(self, realm):
        realm_info = self._fetch_realm_info(realm)
        return int(realm_info["timespan".encode("utf-8")].decode("utf-8"))

    @classmethod
    def configure(cls, **kwargs):
        if "redis" in kwargs:
            if type(kwargs["redis"]) != dict:
                raise RequestsRespectfulConfigError("'redis' key must be a dict")

            expected_redis_keys = ["host", "port", "password", "database"]
            missing_redis_keys = list()

            for expected_redis_key in expected_redis_keys:
                if expected_redis_key not in kwargs["redis"]:
                    missing_redis_keys.append(expected_redis_key)

            if len(missing_redis_keys):
                raise RequestsRespectfulConfigError("'%s' %s missing from the 'redis' configuration key" % (
                    ", ".join(missing_redis_keys),
                    "is" if len(missing_redis_keys) == 1 else "are"
                ))
#.........这里部分代码省略.........
开发者ID:beaugunderson,项目名称:requests-respectful,代码行数:103,代码来源:respectful_requester.py


注:本文中的redis.StrictRedis.info方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。