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
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)
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 )
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 ) )
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
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
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
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)
def invalidate_all(): keys = conn.keys('%s*' % conf.get('PCFG_KEY_PREFIX')) return delete(*keys)
def ttl(self): return int(self.cache_conf.get( 'ttl', conf.get('PCFG_DEFAULT_TTL') ))
def chk_status_code(self): u""" кешируем только ответы с определенынми статусами """ return self.response.status_code in conf.get("PCFG_ALLOWED_STATUS_CODES")
def redis_conn(): global _redis if not (_redis and _redis.ping()): _redis = redis.Redis(**conf.get('PCFG_REDIS')) return _redis
def get_logger(): import panacea.config as conf return logging.getLogger(conf.get('PCFG_LOGGER_NAME'))