예제 #1
0
파일: engine.py 프로젝트: klem4/panacea
 def chk_content_type(self):
     u"""
     кешируем только ответы определенного типа
     """
     ct_and_charset = self.response.get("content-type").split(";")
     try:
         return ct_and_charset[0] == conf.get("PCFG_ALLOWED_CONTENT_TYPE")
     except IndexError:
         return False
예제 #2
0
    def handle(self, *args, **options):
        schemes = self.get_schemes()
        if not schemes:
            raise CommandError("Schemes list is empty")

        items = map(
            lambda scheme: {
                'location': self.get_location(scheme),
                'redis_key': self.get_redis_key(scheme)
            }, schemes
        )

        rendered_config = render_to_string(
            'config.html', {
                'items': items,
                'redis':conf.get('PCFG_REDIS'),
                'default_type': conf.get('PCFG_ALLOWED_CONTENT_TYPE')
            }
        )

        self.stdout.write(rendered_config)
예제 #3
0
    def _get_part(self, part_type, request):
        data_dict = getattr(request, part_type)
        separator = conf.get('PCFG_VALUES_SEPARATOR')

        # cначала идут дефолтные значения, затем
        # кастомные для данной схемы

        keys = self.get_all_part_keys(part_type)

        return separator.join(
            "%s=%s" % (key, data_dict.get(key, '')) for key in keys
        )
예제 #4
0
 def generate_key_structure(self):
     u"""
     полный формат ключа, по умолчанию
     prefix}{path}{querystring_args}{headers}{cookies}
     """
     separator = conf.get("PCFG_PART_SEPARATOR")
     return "{prefix}{alias}:{path}%s%s" % (
             separator,
             separator.join(
             "{%s}" % part for part in self.key_defaults_order
         )
     )
예제 #5
0
def invalidate_alias(aliases):
    if not isinstance(aliases, (list, tuple)):
        aliases = [aliases,]

    key_patterns = map(
        lambda alias: "%s%s*" % (
            conf.get('PCFG_KEY_PREFIX'), alias
        ),
        aliases
    )

    results = []
    for p in key_patterns:
        results += delete(*conn.keys(p))

    return results
예제 #6
0
    def generate_key_parts(self, request):
        """
        возвращает словарь со сформированными частями
        ключа
        """
        key_parts = {
            'prefix': conf.get('PCFG_KEY_PREFIX'),
            'alias': self.alias,
            'path': request.path,
        }

        for part in self.key_defaults_order:
            key_parts[part] = getattr(
                self, '_generate_part_%s' % part.lower())(request)

        return key_parts
예제 #7
0
파일: engine.py 프로젝트: klem4/panacea
    def allow_caching(self):
        u"""
        проверяем, необходимо ли кешированть
        данный запрос
        """

        # кеширование отключено глобально
        if not conf.get("PCFG_ENABLED", default=False):
            return

        for checker_name in ("method", "status_code", "content_type", "scheme"):
            method_name = "chk_%s" % checker_name
            if hasattr(self, method_name):
                checker_method = getattr(self, "chk_%s" % checker_name)
                if not checker_method():
                    return
            else:
                logger.error("handler not found: %s" % method_name)
                return

        return True
예제 #8
0
    def testWrongStatusCode(self, patched_response, patched_store):
        """
        проверяем, что не кешируем ответы
        в случае неверного кода ответа api
        """

        known_status_codes = sorted(conf.get('PCFG_ALLOWED_STATUS_CODES'))

        some_bad_code = known_status_codes[-1] + 1

        patched_response.__get__ = Mock(return_value=some_bad_code)
        patched_response.__set__ = Mock()

        r = self.client.get(self.url1)
        self.assertEqual(r.status_code, some_bad_code)
        self.assertFalse(patched_store.called)

        for status in known_status_codes:
             patched_response.__get__ = Mock(return_value=status)
             r = self.client.get(self.url1)
             self.assertEqual(r.status_code, status)
             self.assertTrue(patched_store.called)
예제 #9
0
def invalidate_all():
    keys = conn.keys('%s*' % conf.get('PCFG_KEY_PREFIX'))
    return delete(*keys)
예제 #10
0
 def ttl(self):
     return int(self.cache_conf.get(
         'ttl',
         conf.get('PCFG_DEFAULT_TTL')
     ))
예제 #11
0
파일: engine.py 프로젝트: klem4/panacea
 def chk_status_code(self):
     u"""
     кешируем только ответы с определенынми статусами
     """
     return self.response.status_code in conf.get("PCFG_ALLOWED_STATUS_CODES")
예제 #12
0
def redis_conn():
    global _redis
    if not (_redis and _redis.ping()):
        _redis = redis.Redis(**conf.get('PCFG_REDIS'))
    return _redis
예제 #13
0
def get_logger():
    import panacea.config as conf
    return logging.getLogger(conf.get('PCFG_LOGGER_NAME'))