def process_response(self, request, response):
        """Sets the cache, if needed."""
        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        if response.streaming or response.status_code != 200:
            return response

        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        patch_response_headers(response, timeout)
        if timeout:
            cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout)
                )
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 2
0
    def process_response(self, request, response):
        """Set the cache, if needed."""
        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        if response.streaming or response.status_code not in (200, 304):
            return response

        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        patch_response_headers(response, timeout)
        if timeout and response.status_code == 200:
            cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout)
                )
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 3
0
    def process_response(self, request, response):
        if not self._should_update_cache(request, response):
            return response

        if response.streaming or response.status_code != 200:
            return response

        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            return response

        if (request.path.startswith('/admin/') or request.path.startswith('/sitemap') or
                request.path[-12:] == '/rss/yandex/' or request.path == 'sidebar.json'):
            return response

        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            return response
        #patch_response_headers(response, 5)
        if timeout:
            cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(lambda r: self.cache.set(cache_key, r, timeout))
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 4
0
    def process_response(self, request, response):
        """Sets the cache, if needed."""
        #if not self._should_update_cache(request, response):
        #    # We don't need to update the cache, just return.
        #    return response

        if response.streaming or response.status_code != 200:
            return response
        
        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        timeout = get_max_age(response)
        if timeout == None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        patch_response_headers(response, timeout)
        if timeout:
            cache_key = "%s-%s" % (self.key_prefix, request.get_full_path())
            #raise ValueError(cache_key)
            if hasattr(response, 'render') and isinstance(response.render, collections.Callable):
                response.add_post_render_callback(
                    lambda r: cache._cache.set(cache_key.encode("utf-8"), zlib.compress(r.content, 9), timeout)
                )
            else:
                # we use the highest compression level, because since it is cached we hope for it to pay off
                cache._cache.set(cache_key.encode("utf-8"), zlib.compress(response.content, 9), timeout)
        return response
Exemplo n.º 5
0
 def _should_update_cache(self, request, response):
     if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
         return False
     if self.cache_anonymous_only and has_vary_header(response, 'Cookie'):
         assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware."
         if request.user.is_authenticated():
             # Don't cache user-variable requests from authenticated users.
             return False
     return True
Exemplo n.º 6
0
    def process_response(self, request, response):
        if request.COOKIES.get(
                'view_uncached') == 'true' and request.user.is_authenticated:
            return response
        else:
            middleware_cache_tags = self.cache_tags if self.cache_tags else []

            if not self._should_update_cache(request, response):
                return response

            if response.streaming or response.status_code not in (200, 304):
                return response

            # Don't cache responses that set a user-specific (and maybe security
            # sensitive) cookie in response to a cookie-less request.
            if not request.COOKIES and response.cookies and has_vary_header(
                    response, 'Cookie'):
                return response

            # Don't cache a response with 'Cache-Control: private'
            if 'private' in response.get('Cache-Control', ()):
                return response

            # Try to get the timeout from the "max-age" section of the "Cache-
            # Control" header before reverting to using the default cache_timeout
            # length.
            timeout = get_max_age(response)
            if timeout is None:
                timeout = self.cache_timeout
            elif timeout == 0:
                # max-age was set to 0, don't bother caching.
                return response
            patch_response_headers(response, timeout)
            if response.has_header('X-Additional-Cache-Tags'):
                middleware_cache_tags = response.__getitem__(
                    'X-Additional-Cache-Tags').split(",") + self.cache_tags
            if timeout and response.status_code == 200:
                cache_key = learn_cache_key(request,
                                            response,
                                            timeout,
                                            self.key_prefix,
                                            cache=self.cache)
                # add this cache_key to a cache_keys cache with tags

                cache.add_cache_key(request,
                                    cache_key,
                                    tags=middleware_cache_tags)

                if hasattr(response, 'render') and callable(response.render):
                    response.add_post_render_callback(
                        lambda r: self.cache.set(cache_key, r, timeout))
                else:
                    self.cache.set(cache_key, response, timeout)
            return response
Exemplo n.º 7
0
    def process_response(self, request, response):
        """
        RUS: Возвращает ответ сервера, если пользователь идентифицирован.
        """
        if request.user.is_authenticated():
            return response
        """Sets the cache, if needed."""
        if not self._should_update_cache(request, response):
            return response
        # RUS: Возвращает ответ сервера, если не было обновления кэша.

        if response.streaming or response.status_code != 200:
            return response
        # RUS: Возвращает ответ сервера, если, у атрибута HttpResponse.streaming статус False
        # или код ответа не равен 200.

        # Не кэширует ответы сервера, которые устанавливают специфичные для пользователя (и, возможно,
        # чувствительные к безопасности ) cookie в ответ на запрос без cookie
        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if not request.COOKIES and response.cookies and has_vary_header(
                response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        # Возвращает максимальный возраст из заголовка Cache-Control ответа в виде целого числа (
        # Пытается получить время хранения кэша из заголовка Cache-Control.
        # При его отсутствии, время хранения кэша равно значению по умолчанию,
        # если же установлено равным 0, возвращается некэшированный ответ сервера

        patch_response_headers(response, timeout)
        if timeout:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        self.key_prefix,
                                        cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout))
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 8
0
    def process_response(self, request, response):
        """Sets the cache, if needed."""

        # TODO
        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        # 不是流响应,不是200码
        if response.streaming or response.status_code != 200:
            return response

        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        # 请求没有cookie,但是处理过程中设置了cookie,并且Vary包含了Cookie,直接返回
        # 分析:因为缓存服务器收到请求是没有Cookie的,然后返回的告诉他类似的请求根据Cookie
        # 来判断是否使用缓存,这样,下一个没有Cookie的人访问该URL则会拿到之前的人
        # 的Cookie中的数据
        if not request.COOKIES and response.cookies and has_vary_header(
                response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        # 首先使用response中设置的max_age(根据Cache-Control部分),如果没有设置
        # 则使用setting中的.
        # 分析:setting中的是最后的依据,如果设置过则按照设置过的来
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        # 设置ETag, Last-Modified, Expires 和 Cache-Control的max-age部分,都用于缓存控制
        patch_response_headers(response, timeout)

        if timeout:
            # 拿到cache——key,该方法设置了header_key,返回的是page_key
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        self.key_prefix,
                                        cache=self.cache)
            # 如果有render,则设置回调,在render之后缓存.
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout))
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 9
0
 def test_has_vary_header(self):
     possible_headers = ('cookie', 'accept-encoding')
     sample_values = (
         # Vary header value, has_vary_header value for the possible_headers
         ('Cookie', (True, False)),
         ('COOKIE', (True, False)),
         ('Accept-Encoding', (False, True)),
         ('Cookie, Accept-Encoding', (True, True)),
         ('Accept-Encoding, Cookie', (True, True)),
         ('Cookie    ,     Accept-Encoding', (True, True)),
     )
     for vary_header, results in sample_values:
         response = HttpResponse()
         response['Vary'] = vary_header
         for test_header, result in zip(possible_headers, results):
             self.assertEqual(has_vary_header(response, test_header), result)
Exemplo n.º 10
0
    def process_response(self, request, response):
        """Set the cache, if needed."""
        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        if response.streaming or response.status_code not in (200, 304):
            return response

        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if (not request.COOKIES and response.cookies
                and has_vary_header(response, "Cookie")):
            return response

        # Don't cache a response with 'Cache-Control: private'
        if "private" in response.get("Cache-Control", ()):
            return response

        # Page timeout takes precedence over the "max-age" and the default
        # cache timeout.
        timeout = self.page_timeout
        if timeout is None:
            # The timeout from the "max-age" section of the "Cache-Control"
            # header takes precedence over the default cache timeout.
            timeout = get_max_age(response)
            if timeout is None:
                timeout = self.cache_timeout
            elif timeout == 0:
                # max-age was set to 0, don't cache.
                return response
        patch_response_headers(response, timeout)
        if timeout and response.status_code == 200:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        self.key_prefix,
                                        cache=self.cache)
            if hasattr(response, "render") and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout))
            else:
                self.cache.set(cache_key, response, timeout)
        return response
Exemplo n.º 11
0
    def process_response(self, request, response):
        if request.path != '/status':
            cache_entry = Model('cache').facade.get_or_create(
                request.build_absolute_uri())
            cache_entry.requests += 1
            cache_entry.save()

        if not (hasattr(request, '_cache_update_cache')
                and request._cache_update_cache):
            return response

        response['Object-Cache'] = 'MISS'

        if response.streaming or response.status_code not in (200, 304):
            return response

        if not request.COOKIES and response.cookies and has_vary_header(
                response, 'Cookie'):
            return response

        if 'private' in response.get('Cache-Control', ()):
            return response

        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            return response

        patch_response_headers(response, timeout)

        if timeout and response.status_code == 200:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        self.key_prefix,
                                        cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: self.cache.set(cache_key, r, timeout))
            else:
                self.cache.set(cache_key, response, timeout)

        return response
Exemplo n.º 12
0
    def process_response(self, request: WSGIRequest,
                         response: HttpResponse) -> HttpResponse:
        if not wagtailcache_settings.WAGTAIL_CACHE:
            return response

        if getattr(request, "_wagtailcache_skip", False):
            # If we should skip this response, add header and return.
            _patch_header(response, Status.SKIP)
            return response

        if not getattr(request, "_wagtailcache_update", False):
            # We don't need to update the cache, just return.
            return response

        # Check if the response is cacheable
        # Don't cache private or no-cache responses.
        # Do cache 200, 301, 302, 304, and 404 codes so that wagtail doesn't
        #   have to repeatedly look up these URLs in the database.
        # Don't cache streaming responses.
        is_cacheable = (CacheControl.NOCACHE.value not in response.get(
            "Cache-Control", "")
                        and CacheControl.PRIVATE.value not in response.get(
                            "Cache-Control", "")
                        and response.status_code in (200, 301, 302, 304, 404)
                        and not response.streaming)
        # Don't cache 200 responses that set a user-specific cookie in response
        # to a cookie-less request (e.g. CSRF tokens).
        if is_cacheable and response.status_code == 200:
            is_cacheable = not (not request.COOKIES and response.cookies
                                and has_vary_header(response, "Cookie"))

        # Allow the user to override our caching decision.
        for fn in hooks.get_hooks("is_response_cacheable"):
            result = fn(response, is_cacheable)
            if isinstance(result, bool):
                is_cacheable = result

        # If we are not allowed to cache the response, just return.
        if not is_cacheable:
            # Add response header to indicate this was intentionally not cached.
            _patch_header(response, Status.SKIP)
            return response

        # Try to get the timeout from the ``max-age`` section of the
        # ``Cache-Control`` header before reverting to using the cache's
        # default.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self._wagcache.default_timeout
        patch_response_headers(response, timeout)
        if timeout:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        None,
                                        cache=self._wagcache)
            if isinstance(response, SimpleTemplateResponse):
                response.add_post_render_callback(
                    lambda r: self._wagcache.set(cache_key, r, timeout))
            else:
                self._wagcache.set(cache_key, response, timeout)

            # Add a response header to indicate this was a cache miss.
            _patch_header(response, Status.MISS)

        return response
Exemplo n.º 13
0
    def process_response(self, request, response):
<<<<<<< HEAD
        """Sets the cache, if needed."""
=======
        """Set the cache, if needed."""
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        if response.streaming or response.status_code not in (200, 304):
            return response

        # Don't cache responses that set a user-specific (and maybe security
        # sensitive) cookie in response to a cookie-less request.
        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the default cache_timeout
        # length.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = self.cache_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        patch_response_headers(response, timeout)
        if timeout and response.status_code == 200:
            cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
            if hasattr(response, 'render') and callable(response.render):
Exemplo n.º 14
0
    def process_response(self, request, response):
        if not wagtailcache_settings['WAGTAIL_CACHE']:
            return response

        if not self._should_update_cache(request, response):
            # We don't need to update the cache, just return.
            return response

        # Check if the response is cacheable
        # Don't cache private or no-cache responses.
        # Do cache 200, 301, 302, 304, and 404 codes so that wagtail doesn't have to repeatedly look up these URLs in the database.
        # Don't cache streaming responses.
        is_cacheable = \
            'no-cache' not in response.get('Cache-Control', ()) and \
            'private' not in response.get('Cache-Control', ()) and \
            response.status_code in (200, 301, 302, 304, 404) and \
            not response.streaming
        # Don't cache 200 responses that set a user-specific cookie in response to a cookie-less request (e.g. CSRF tokens).
        if is_cacheable and response.status_code == 200:
            is_cacheable = not (not request.COOKIES and response.cookies
                                and has_vary_header(response, 'Cookie'))

        # Allow the user to override our caching decision.
        for fn in hooks.get_hooks('is_response_cacheable'):
            result = fn(response, is_cacheable)
            if isinstance(result, bool):
                is_cacheable = result

        # If we are not allowed to cache the response, just return.
        if not is_cacheable:
            # Add a response header to indicate this was intentionally not cached.
            if wagtailcache_settings['WAGTAIL_CACHE_HEADER']:
                response[
                    wagtailcache_settings['WAGTAIL_CACHE_HEADER']] = 'skip'
            return response

        # Try to get the timeout from the "max-age" section of the "Cache-
        # Control" header before reverting to using the cache's default.
        timeout = get_max_age(response)
        if timeout is None:
            timeout = _wagcache.default_timeout
        elif timeout == 0:
            # max-age was set to 0, don't bother caching.
            return response
        patch_response_headers(response, timeout)
        if timeout:
            cache_key = learn_cache_key(request,
                                        response,
                                        timeout,
                                        None,
                                        cache=_wagcache)
            if hasattr(response, 'render') and callable(response.render):
                response.add_post_render_callback(
                    lambda r: _wagcache.set(cache_key, r, timeout))
            else:
                _wagcache.set(cache_key, response, timeout)

            # Add a response header to indicate this was a cache miss.
            if wagtailcache_settings['WAGTAIL_CACHE_HEADER']:
                response[
                    wagtailcache_settings['WAGTAIL_CACHE_HEADER']] = 'miss'

        return response
Exemplo n.º 15
0
"""
Exemplo n.º 16
0
    def process_response(self, request, response):
        if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
            add_never_cache_headers(response)

        return response