當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。