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


Python redis.Redis方法代码示例

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


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

示例1: save_session

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def save_session(self, app, session, response):
        """Save session to Redis."""
        domain = self.get_cookie_domain(app)
        path = url_for('main', _external=False)

        if not session:
            self.redis.delete(self.prefix + session.sid)
            if session.modified:
                response.delete_cookie(app.session_cookie_name,
                                       domain=domain, path=path)
        else:
            redis_exp = self.get_redis_expiration_time(app, session)
            cookie_exp = self.get_expiration_time(app, session)
            if session.modified:
                val = self.serializer.dumps(dict(session))
                self.redis.setex(self.prefix + session.sid,
                                 int(redis_exp.total_seconds()), val)
            else:
                self.redis.expire(self.prefix + session.sid,
                                  int(redis_exp.total_seconds()))
            response.set_cookie(app.session_cookie_name, session.sid,
                                expires=cookie_exp, httponly=True,
                                domain=domain, path=path, secure=True) 
开发者ID:toolforge,项目名称:video2commons,代码行数:25,代码来源:redisession.py

示例2: open_session

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def open_session(self, app, request):
        """Get session from Redis / start a new session."""
        sid = request.cookies.get(app.session_cookie_name)
        if sid:
            val = self.redis.get(self.prefix + sid)
            if val is not None:
                try:
                    data = self.serializer.loads(val)
                except ValueError:
                    pass
                else:
                    return self.session_class(data, sid=sid)

        # SECURITY: If the session id is invalid, we create a new one, to
        # prevent cookie-injection.
        # https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-zheng.pdf
        sid = self.generate_sid()
        return self.session_class(sid=sid, new=True) 
开发者ID:toolforge,项目名称:video2commons,代码行数:20,代码来源:redisession.py

示例3: __init__

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def __init__(self, key_prefix, limit, per):
        global redis
        if redis is None and current_app.config['USE_RATE_LIMITS']:
            if current_app.config['TESTING']:
                redis = FakeRedis()
            else:
                redis = Redis()

        self.reset = (int(time.time()) // per) * per + per
        self.key = key_prefix + str(self.reset)
        self.limit = limit
        self.per = per
        p = redis.pipeline()
        p.incr(self.key)
        p.expireat(self.key, self.reset + self.expiration_window)
        self.current = min(p.execute()[0], limit) 
开发者ID:miguelgrinberg,项目名称:api-pycon2014,代码行数:18,代码来源:rate_limit.py

示例4: plugin

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def plugin(srv, item):
    """ redispub. Expects addrs to contain (channel) """

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    host = item.config.get('host', 'localhost')
    port = int(item.config.get('port', 6379))

    try:
        rp = redis.Redis(host, port)
    except Exception as e:
        srv.logging.warn("Cannot connect to redis on %s:%s : %s" % (host, port, e))
        return False

    channel = item.addrs[0]
    text = item.message

    try:
        rp.publish(channel, text)
    except Exception as e:
        srv.logging.warn("Cannot publish to redis on %s:%s : %s" % (host, port, e))
        return False

    return True 
开发者ID:jpmens,项目名称:mqttwarn,代码行数:26,代码来源:redispub.py

示例5: __init__

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def __init__(self, host='localhost', port=6379, password=None,
                 db=0, default_timeout=300, key_prefix=None, **kwargs):
        BaseCache.__init__(self, default_timeout)
        if isinstance(host, string_types):
            try:
                import redis
            except ImportError:
                raise RuntimeError('no redis module found')
            if kwargs.get('decode_responses', None):
                raise ValueError('decode_responses is not supported by '
                                 'RedisCache.')
            self._client = redis.Redis(host=host, port=port, password=password,
                                       db=db, **kwargs)
        else:
            self._client = host
        self.key_prefix = key_prefix or '' 
开发者ID:jpush,项目名称:jbox,代码行数:18,代码来源:cache.py

示例6: CheckServer

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def CheckServer():
    mongo_cmd='lsof -i:27017 | grep LISTEN'
    redis_cmd='lsof -i:6379 | grep LISTEN'
    p1=subprocess.Popen(mongo_cmd,shell=True,stdout=subprocess.PIPE)
    p2=subprocess.Popen(redis_cmd,shell=True,stdout=subprocess.PIPE)
    r1=len(p1.stdout.readlines())
    r2=len(p2.stdout.readlines())
    msg=''
    if r1==0:
        msg+='<p><B>MongoDB未运行<B></p>'
    if r2==0:
        msg+='<p><B>Redis未运行<B></p>'
    p1.terminate()
    p2.terminate()
    if r1==0 or r2==0:
        return msg,False
    else:
        return msg,True 
开发者ID:abbeyokgo,项目名称:PyOne,代码行数:20,代码来源:header.py

示例7: handle_issue

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def handle_issue(webhook_payload, db):
    """
    Handler for newly opened issues
    :param webhook_payload: json data from webhook
    :param db: Redis instance
    :return:
    """
    release_bot, logger = set_configuration(webhook_payload, db=db, issue=True)

    logger.info("Resolving opened issue")
    release_bot.git.pull()
    try:
        release_bot.load_release_conf()
        if (release_bot.new_release.trigger_on_issue and
                release_bot.find_open_release_issues()):
            if release_bot.new_release.labels is not None:
                release_bot.project.add_issue_labels(
                    release_bot.new_pr.issue_number,
                    release_bot.new_release.labels)
            release_bot.make_release_pull_request()
    except ReleaseException as exc:
        logger.error(exc) 
开发者ID:user-cont,项目名称:release-bot,代码行数:24,代码来源:celery_task.py

示例8: handle_pr

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def handle_pr(webhook_payload, db):
    """
    Handler for merged PR
    :param webhook_payload: json data from webhook
    :param db: Redis instance
    :return:
    """
    release_bot, logger = set_configuration(webhook_payload, db=db, issue=False)

    logger.info("Resolving opened PR")
    release_bot.git.pull()
    try:
        release_bot.load_release_conf()
        if release_bot.find_newest_release_pull_request():
            release_bot.make_new_github_release()
            # Try to do PyPi release regardless whether we just did github release
            # for case that in previous iteration (of the 'while True' loop)
            # we succeeded with github release, but failed with PyPi release
            release_bot.make_new_pypi_release()
    except ReleaseException as exc:
        logger.error(exc)

    msg = ''.join(release_bot.github.comment)
    release_bot.project.pr_comment(release_bot.new_release.pr_number, msg)
    release_bot.github.comment = []  # clean up 
开发者ID:user-cont,项目名称:release-bot,代码行数:27,代码来源:celery_task.py

示例9: _setup_stats

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def _setup_stats(self):
        '''
        Sets up the stats collection
        '''
        self.stats_dict = {}

        redis_conn = redis.Redis(host=self.settings['REDIS_HOST'],
                                 port=self.settings['REDIS_PORT'],
                                 db=self.settings.get('REDIS_DB'))

        try:
            redis_conn.info()
            self.logger.debug("Connected to Redis in StatsCollector Setup")
            self.redis_conn = redis_conn
        except ConnectionError:
            self.logger.warn("Failed to connect to Redis in StatsCollector"
                             " Setup, no stats will be collected")
            return

        if self.settings['STATS_TOTAL']:
            self._setup_stats_total(redis_conn)

        if self.settings['STATS_PLUGINS']:
            self._setup_stats_plugins(redis_conn) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:26,代码来源:kafka_monitor.py

示例10: handle

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def handle(self, dict):
        '''
        Processes a vaild stats request

        @param dict: a valid dictionary object
        '''
        # format key
        key = "statsrequest:{stats}:{appid}".format(
                stats=dict['stats'],
                appid=dict['appid'])

        self.redis_conn.set(key, dict['uuid'])

        dict['parsed'] = True
        dict['valid'] = True
        self.logger.info('Added stat request to Redis', extra=dict) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:18,代码来源:stats_handler.py

示例11: handle

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def handle(self, dict):
        '''
        Processes a vaild action request

        @param dict: a valid dictionary object
        '''
        # format key
        key = "{action}:{spiderid}:{appid}".format(
                action=dict['action'],
                spiderid=dict['spiderid'],
                appid=dict['appid'])

        if "crawlid" in dict:
            key = key + ":" + dict['crawlid']

        self.redis_conn.set(key, dict['uuid'])

        dict['parsed'] = True
        dict['valid'] = True
        self.logger.info('Added action to Redis', extra=dict) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:22,代码来源:action_handler.py

示例12: setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def setup(self, settings):
        '''
        Setup redis and tldextract
        '''
        self.extract = tldextract.TLDExtract()
        self.redis_conn = redis.Redis(host=settings['REDIS_HOST'],
                                      port=settings['REDIS_PORT'],
                                      db=settings.get('REDIS_DB'))

        try:
            self.redis_conn.info()
            self.logger.debug("Connected to Redis in ZookeeperHandler")
        except ConnectionError:
            self.logger.error("Failed to connect to Redis in ZookeeperHandler")
            # plugin is essential to functionality
            sys.exit(1) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:18,代码来源:zookeeper_handler.py

示例13: setup

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def setup(self, settings):
        '''
        Setup redis and tldextract
        '''
        self.extract = tldextract.TLDExtract()
        self.redis_conn = redis.Redis(host=settings['REDIS_HOST'],
                                      port=settings['REDIS_PORT'],
                                      db=settings.get('REDIS_DB'))

        try:
            self.redis_conn.info()
            self.logger.debug("Connected to Redis in ScraperHandler")
        except ConnectionError:
            self.logger.error("Failed to connect to Redis in ScraperHandler")
            # plugin is essential to functionality
            sys.exit(1) 
开发者ID:istresearch,项目名称:scrapy-cluster,代码行数:18,代码来源:scraper_handler.py

示例14: __init__

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def __init__(self, host='localhost', port=6379, password=None,
                 db=0, default_timeout=300, key_prefix=None, **kwargs):
        BaseCache.__init__(self, default_timeout)
        if host is None:
            raise ValueError('RedisCache host parameter may not be None')
        if isinstance(host, string_types):
            try:
                import redis
            except ImportError:
                raise RuntimeError('no redis module found')
            if kwargs.get('decode_responses', None):
                raise ValueError('decode_responses is not supported by '
                                 'RedisCache.')
            self._client = redis.Redis(host=host, port=port, password=password,
                                       db=db, **kwargs)
        else:
            self._client = host
        self.key_prefix = key_prefix or '' 
开发者ID:pallets,项目名称:cachelib,代码行数:20,代码来源:redis.py

示例15: connect

# 需要导入模块: import redis [as 别名]
# 或者: from redis import Redis [as 别名]
def connect(self):
        ''' Open Connection to Redis '''
        if "password" not in self.config['datastore']['plugins']['redis'].keys():
            password = None
        else:
            password = self.config['datastore']['plugins']['redis']['password']
        try:
            self.dbc = redis.Redis(
                host=self.config['datastore']['plugins']['redis']['host'],
                port=self.config['datastore']['plugins']['redis']['port'],
                password=None,
                db=self.config['datastore']['plugins']['redis']['db'])
        except Exception as e:
            raise Exception("Failed to connect to Redis: {0}".format(e.message))
        self.initialize_db()
        return True 
开发者ID:madflojo,项目名称:automatron,代码行数:18,代码来源:__init__.py


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