• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python client.StrictRedis类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: rfunc

def rfunc(info):
    #
    info.setdefault('host', '127.0.0.1')
    info.setdefault('port', 6379)

    #
    conn_kwargs = dict(
        host=info['host'],
        port=int(info['port']),
    )

    #
    print('# Connect')
    print(pformat(conn_kwargs, indent=4, width=1))

    #
    conn = None

    try:
        #
        conn = StrictRedis(**conn_kwargs)

        #
        res = '\n'.join('{:<30}: {}'.format(k, v) for k, v in conn.info().items())

        #
        print('# Result')
        print(res)

    finally:
        #
        conn = None
开发者ID:AoiKuiyuyou,项目名称:AoikQueryHurry,代码行数:32,代码来源:main.py


示例2: Record

class Record(object):
    def __init__(self,host='127.0.0.1',port=6379):         
        self.r=StrictRedis()
    
    def run(self):
        while True:
            value=self.r.rpop('alerts')
            if value:
                obj=json.loads(value)
                keyredis=obj['src_ip']+'_'+str(obj['src_port'])+'_'+ obj['dest_ip']+'_'+str(obj['dest_port'])
                entry=self.r.get(keyredis)
                if entry:
                    restruct=json.loads(entry)
                else:
                    restruct={}
                if not 'http' in restruct:
                    restruct['http']=[]
                if not 'alerts' in restruct:
                    restruct['alerts']=[]
                if not 'files' in restruct:
                    restruct['files']=[]  
                if 'alert' in obj:    
                    restruct['alerts'].append(obj['alert']['signature'])
                if 'fileinfo' in obj:
                    restruct['files'].append(obj['fileinfo'])
                if 'http' in obj:
                    restruct['http'].append(obj['http'])
                if len(restruct)>0:
                    self.r.set(keyredis, json.dumps(restruct))
            else:
                sleep(1)
开发者ID:SekoiaLab,项目名称:Suricata-Redis,代码行数:31,代码来源:record.py


示例3: redis

class redis(object):
    def __init__(self,host='127.0.0.1',port=6379):
        self.r = StrictRedis(host,port)
    def rec(self,k,v):
        self.r.set(k, v)
    def rpush(self,v):
        self.r.rpush('alerts',v)
开发者ID:SekoiaLab,项目名称:Suricata-Redis,代码行数:7,代码来源:json2redis.py


示例4: main

def main():
    r = StrictRedis(host='localhost', port=6379, db=0)

    ps = r.pubsub()

    ps.subscribe("logs")
    data = ps.listen()
    print(data)
开发者ID:zenweasel,项目名称:redis-manager,代码行数:8,代码来源:logger.py


示例5: rewrite_redis_aof_job

def rewrite_redis_aof_job():
    current_veil_env = get_current_veil_env()
    if not hasattr(current_veil_env.config, 'redis_servers'):
        return
    for host, port in current_veil_env.config.redis_servers:
        client = StrictRedis(host=host, port=port)
        if client.config_get('appendonly')['appendonly'] != 'yes':
            continue
        client.bgrewriteaof()
开发者ID:,项目名称:,代码行数:9,代码来源:


示例6: __init_rd

 def __init_rd(self, master=False):
     if self.rd is None:
         if master:
             self.rd = StrictRedis(host=_redis_servers[0][0], port=_redis_servers[0][1], db=_redis_servers[0][2])
             self._master_rd = True
         else:
             server = random.choice(_redis_servers)
             self.rd = StrictRedis(host=server[0], port=server[1], db=server[2])
             self._master_rd = False
     elif master and not self._master_rd:
         self.rd = StrictRedis(host=_redis_servers[0][0], port=_redis_servers[0][1], db=_redis_servers[0][2])
         self._master_rd = True
开发者ID:eluzix,项目名称:pyramid_redis_session,代码行数:12,代码来源:__init__.py


示例7: __init__

 def __init__(self):
     # Load the GeoIP databases into class attributes since they each need 20+ MB in memory
     if not self.__class__._geoip4:
         self.__class__._geoip4 = GeoIP(Config.GEOIP_PATH_V4, MEMORY_CACHE)
     if not self.__class__._geoip6:
         self.__class__._geoip6 = GeoIP(Config.GEOIP_PATH_V6, MEMORY_CACHE)
     self.redis = StrictRedis(Config.REDIS['HOST'], Config.REDIS['PORT'], Config.REDIS['DB'])
开发者ID:ulope,项目名称:nearest_pypi,代码行数:7,代码来源:distance.py


示例8: redis

def redis(app=None):
    app = app_or_default(app)

    if not hasattr(app, "redbeat_redis") or app.redbeat_redis is None:
        app.redbeat_redis = StrictRedis.from_url(app.conf.REDBEAT_REDIS_URL, decode_responses=True)

    return app.redbeat_redis
开发者ID:sibson,项目名称:redbeat,代码行数:7,代码来源:schedulers.py


示例9: flushdb

 def flushdb(self):
     """Destroy every shard's db
     """
     for pool in self.pool_map.values():
         con = StrictRedis.from_url(pool.url, connection_pool=pool)
         self.log.debug("flushing shard member: %s", con)
         con.flushdb()
         del con
开发者ID:nficano,项目名称:jotonce.com,代码行数:8,代码来源:redis_con.py


示例10: __init__

 def __init__(self, dispatcher, db_host, db_port, db_num, db_pw):
     self.dispatcher = dispatcher
     pool = ConnectionPool(max_connections=2, db=db_num, host=db_host, port=db_port, password=db_pw)
     self.redis = StrictRedis(connection_pool=pool)
     self.encoder = JSONEncoder()
     self.decoder = JSONDecoder()
     self.class_map = {}
     self.object_map = {}
开发者ID:ldevesine,项目名称:Lampost-Mud,代码行数:8,代码来源:dbconn.py


示例11: __init__

 def __init__(self,config):
     if self._validateConfig(config):
         self._r = StrictRedis(host=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_HOST],
                                     port=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_PORT],
                                     db=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_DB])
         logger.debug("Obtained internal redis handler" + str(self._r))
     else:
         raise BaseException("Error validating config ")
开发者ID:davidfrigola,项目名称:pype,代码行数:8,代码来源:datasource.py


示例12: __init__

 def __init__(self, config, section):
     from redis.client import StrictRedis
     self.conn = StrictRedis(
         config.get(section, 'redis-server'),
         config.getint(section, 'redis-port'),
         config.getint(section, 'redis-db'),
         decode_responses=True
     )
开发者ID:RestAuth,项目名称:apache2-extauth,代码行数:8,代码来源:restauth-extauth.py


示例13: __init__

 def __init__(self, redis_connection=None, locker=None, *args, **kwargs):
     self.__redis_connection = redis_connection
     if self.__redis_connection is None:
          self.__redis_connection = StrictRedis.from_url(current_app.conf.CELERY_REDIS_SCHEDULER_URL)
     self._schedule = EntryProxy(self.__redis_connection)
     self._locker = locker
     if self._locker is None:
         self._locker = Redlock([current_app.conf.CELERY_REDIS_SCHEDULER_URL])
     super(ChardScheduler, self).__init__(*args, **kwargs)
开发者ID:SPSCommerce,项目名称:swiss-chard,代码行数:9,代码来源:scheduler.py


示例14: details

def details(topic, pages):
    client = StrictRedis()
    with client.pipeline(transaction=False) as pipeline:
        pipeline.hgetall(topic)
        pipeline.zcard('{}/pages'.format(topic))
        pipeline.zrange('{}/pages'.format(topic), pages * -1, -1, withscores=True)
        results = pipeline.execute()

    def header(label):
        return '\n'.join(('-' * 80, label, '-' * 80))

    print header('CONFIGURATION')
    print tabulate.tabulate(results[0].items(), headers=('key', 'value'))

    print ''

    print header('PAGES ({} total)'.format(results[1]))
    print tabulate.tabulate(results[2], headers=('page', 'offset'))
开发者ID:tkaemming,项目名称:kafkaesque,代码行数:18,代码来源:__main__.py


示例15: RedisDataSource

class RedisDataSource(AbstractDataSource):

    _r = None
    def __init__(self,config):
        if self._validateConfig(config):
            self._r = StrictRedis(host=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_HOST],
                                        port=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_PORT],
                                        db=config[REDIS_DATASOURCE_CONFIG][REDIS_DATASOURCE_CONFIG_DB])
            logger.debug("Obtained internal redis handler" + str(self._r))
        else:
            raise BaseException("Error validating config ")


    def update(self,item):
        self.store(item)

    def store(self,item):
        self._r.set(item.getHash(), item.getValue())

    def get(self,item):
        return self._r.get(item.getHash())

    def exists(self,item):
        return self.get(item) is not None

    def all(self):

        result = []
        # Obtain all keys
        keys = self._r.keys()

        #For each key, get value
        for k in keys:
            value = self._r.get(k)
            result.append(BaseItem({"origin":"redis"},value))
        #return result
        return result

    def _validateConfig(self,config):

        validator = MultipleConfigValidator(
                        {VALIDATORS_LIST:[ContainsKeyConfigValidator({KEY_VALUE:REDIS_DATASOURCE_CONFIG})]})
        if not validator.validate(config):
            raise BaseException("Config validation error : does not contain " + REDIS_DATASOURCE_CONFIG)

        # Validate redis datasource config
        validator = MultipleConfigValidator(
                        {VALIDATORS_LIST:[ContainsKeysConfigValidator({KEYS_LIST:[REDIS_DATASOURCE_CONFIG_DB,
                                                                                  REDIS_DATASOURCE_CONFIG_HOST,
                                                                                  REDIS_DATASOURCE_CONFIG_PORT]})]})

        if not validator.validate(config[REDIS_DATASOURCE_CONFIG]):
            raise BaseException("Config validation error : config not complete ")

        return True


    def delete(self,item):
        self._r.delete(item.getHash())
开发者ID:davidfrigola,项目名称:pype,代码行数:59,代码来源:datasource.py


示例16: get_app

def get_app(config=None):
    """
    App factory.

    :param dict config: configuration that can override config
        from `settings.py`
    :return: a new SuperdeskEve app instance
    """
    if config is None:
        config = {}

    config.setdefault('SOURCES', {})
    config['APP_ABSPATH'] = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))

    for key in dir(settings):
        if key.isupper():
            config.setdefault(key, getattr(settings, key))

    media_storage = SuperdeskGridFSMediaStorage
    if config.get('AMAZON_CONTAINER_NAME'):
        from superdesk.storage.amazon.amazon_media_storage import AmazonMediaStorage
        media_storage = AmazonMediaStorage

    app = Eve(
        auth=BearerAuth,
        settings=config,
        data=SuperdeskDataLayer,
        media=media_storage,
        json_encoder=MongoJSONEncoder,
        validator=SuperdeskValidator
    )

    superdesk.app = app
    _set_error_handlers(app)
    app.mail = Mail(app)
    if config.get('REDIS_URL'):
        app.redis = StrictRedis.from_url(config['REDIS_URL'], 0)

    for module_name in app.config['INSTALLED_APPS']:
        app_module = importlib.import_module(module_name)
        try:
            app_module.init_app(app)
        except AttributeError:
            pass

    for resource in config['DOMAIN']:
        app.register_resource(resource, config['DOMAIN'][resource])

    for blueprint in superdesk.BLUEPRINTS:
        prefix = app.api_prefix or None
        app.register_blueprint(blueprint, url_prefix=prefix)

    app.sentry = sentry
    sentry.init_app(app)

    return app
开发者ID:ioanpocol,项目名称:superdesk-content-api,代码行数:56,代码来源:__init__.py


示例17: run_once

def run_once():
    for port in REDIS_PORT.split(','):

        if ',' in REDIS_PORT:
            statsd_prefix = STATSD_PREFIX + '-{}'.format(port)
        else:
            statsd_prefix = STATSD_PREFIX

        redis = StrictRedis(REDIS_HOST, port)

        stats = redis.info()
        stats['keyspaces'] = {}

        for key in stats.keys():
            if key.startswith('db'):
                stats['keyspaces'][key] = stats[key]
                del stats[key]

        out_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        for g in GAUGES:
            if g in stats:
                send_metric(out_sock, '{}.{}'.format(statsd_prefix, g), 'g', float(stats[g]))

        for c in COUNTERS:
            if c in stats:
                send_metric(out_sock, '{}.{}'.format(statsd_prefix, c), 'c', float(stats[c]))

        for ks in stats['keyspaces']:
            for kc in KEYSPACE_COUNTERS:
                if kc in stats['keyspaces'][ks]:
                    send_metric(out_sock, '{}.keyspace.{}'.format(
                        statsd_prefix, kc), 'c',
                    float(stats['keyspaces'][ks][kc]))

            for kg in KEYSPACE_GAUGES:
                if kg in stats['keyspaces'][ks]:
                    send_metric(out_sock, '{}.keyspace.{}'.format(
                        statsd_prefix, kg), 'g',
                        float(stats['keyspaces'][ks][kg]))

        out_sock.close()
        time.sleep(PERIOD)
开发者ID:zapier,项目名称:redis-statsd,代码行数:43,代码来源:app.py


示例18: test_is_rate_limited_script

def test_is_rate_limited_script():
    now = int(time.time())

    client = StrictRedis(db=9)

    # The item should not be rate limited by either key.
    assert map(bool, is_rate_limited(client, ('foo', 'bar'), (1, now + 60, 2, now + 120))) == [False, False]

    # The item should be rate limited by the first key (1).
    assert map(bool, is_rate_limited(client, ('foo', 'bar'), (1, now + 60, 2, now + 120))) == [True, False]

    # The item should still be rate limited by the first key (1), but *not*
    # rate limited by the second key (2) even though this is the third time
    # we've checked the quotas. This ensures items that are rejected by a lower
    # quota don't affect unrelated items that share a parent quota.
    assert map(bool, is_rate_limited(client, ('foo', 'bar'), (1, now + 60, 2, now + 120))) == [True, False]

    assert client.get('foo') == '1'
    assert 59 <= client.ttl('foo') <= 60

    assert client.get('bar') == '1'
    assert 119 <= client.ttl('bar') <= 120
开发者ID:AyrtonRicardo,项目名称:sentry,代码行数:22,代码来源:tests.py


示例19: connection

 def connection(self, node_id):
     if not self.__ready:
         return
     shard = self.shard_node(node_id)
     try:
         pool = self.pool_map.get(self.shard_map.get(shard))
         con = StrictRedis.from_url(pool.url, connection_pool=pool)
         yield con
     except Exception:
         self.log.exception("Something blew up in the Redis context "
                            "manager")
         raise
     finally:
         del con
开发者ID:nficano,项目名称:jotonce.com,代码行数:14,代码来源:redis_con.py


示例20: test_truncate_timeline_script

    def test_truncate_timeline_script(self):
        client = StrictRedis(db=9)

        timeline = 'timeline'

        # Preload some fake records (the contents don't matter.)
        records = list(itertools.islice(self.records, 10))
        for record in records:
            client.zadd(timeline, record.timestamp, record.key)
            client.set(make_record_key(timeline, record.key), 'data')

        with self.assertChanges(lambda: client.zcard(timeline), before=10, after=5):
            truncate_timeline((timeline,), (5,), client)

            # Ensure the early records don't exist.
            for record in records[:5]:
                assert not client.zscore(timeline, record.key)
                assert not client.exists(make_record_key(timeline, record.key))

            # Ensure the later records do exist.
            for record in records[-5:]:
                assert client.zscore(timeline, record.key) == float(record.timestamp)
                assert client.exists(make_record_key(timeline, record.key))
开发者ID:ixc,项目名称:sentry,代码行数:23,代码来源:test_redis.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python redis.hget函数代码示例发布时间:2022-05-26
下一篇:
Python client.Redis类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap