Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Separate max age setting #71

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 13 additions & 18 deletions wagtailcache/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from django.utils.cache import get_max_age
from django.utils.cache import has_vary_header
from django.utils.cache import learn_cache_key
from django.utils.cache import patch_cache_control
from django.utils.cache import patch_response_headers
from django.utils.deprecation import MiddlewareMixin
from wagtail import hooks
Expand Down Expand Up @@ -164,7 +165,7 @@ def _get_cache_key(r: WSGIRequest, c: BaseCache) -> str:


def _learn_cache_key(
r: WSGIRequest, s: HttpResponse, t: int, c: BaseCache
r: WSGIRequest, s: HttpResponse, t: Optional[int], c: BaseCache
) -> str:
"""
Wrapper for Django's learn_cache_key which first strips specific
Expand All @@ -191,7 +192,6 @@ def __init__(self, get_response=None):
def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]:
if not wagtailcache_settings.WAGTAIL_CACHE:
return None

# Check if request is cacheable
# Only cache GET and HEAD requests.
# Don't cache requests that are previews.
Expand All @@ -203,7 +203,6 @@ def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]:
and not getattr(request, "is_preview", False)
and not (hasattr(request, "user") and request.user.is_authenticated)
)

# Allow the user to override our caching decision.
for fn in hooks.get_hooks("is_request_cacheable"):
result = fn(request, is_cacheable)
Expand All @@ -214,16 +213,13 @@ def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]:
setattr(request, "_wagtailcache_update", False)
setattr(request, "_wagtailcache_skip", True)
return None # Don't bother checking the cache.

# Try and get the cached response.
try:
cache_key = _get_cache_key(request, self._wagcache)

# No cache information available, need to rebuild.
if cache_key is None:
setattr(request, "_wagtailcache_update", True)
return None

# We have a key, get the cached response.
response = self._wagcache.get(cache_key)

Expand All @@ -233,12 +229,10 @@ def process_request(self, request: WSGIRequest) -> Optional[HttpResponse]:
setattr(request, "_wagtailcache_error", True)
logger.exception("Could not fetch page from cache backend.")
return None

# No cache information available, need to rebuild.
if response is None:
setattr(request, "_wagtailcache_update", True)
return None

# Hit. Return cached response.
setattr(request, "_wagtailcache_update", False)
return response
Expand Down Expand Up @@ -288,7 +282,6 @@ def process_response(
_chop_response_vary(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
Expand All @@ -308,29 +301,32 @@ def process_response(
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

# Potentially remove the ``Vary: Cookie`` header.
_chop_response_vary(request, 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)
max_age = timeout
if timeout is None:
timeout = self._wagcache.default_timeout
patch_response_headers(response, timeout)
if timeout:
max_age = wagtailcache_settings.WAGTAIL_CACHE_MAX_AGE
if max_age is None:
patch_cache_control(response, no_cache=True)
else:
patch_response_headers(response, max_age)

if timeout != 0:
try:
cache_key = _learn_cache_key(
request, response, timeout, self._wagcache
Expand Down Expand Up @@ -412,10 +408,9 @@ def _wrapped_view_func(
) -> HttpResponse:
# Try to fetch an already cached page from wagtail-cache.
response = FetchFromCacheMiddleware().process_request(request)
if response:
return response
# Since we don't have a response at this point, process the request.
response = view_func(request, *args, **kwargs)
if response is None:
# Since we don't have a response at this point, process the request.
response = view_func(request, *args, **kwargs)
# Cache the response.
response = UpdateCacheMiddleware().process_response(request, response)
return response
Expand Down
1 change: 1 addition & 0 deletions wagtailcache/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class _DefaultSettings:
WAGTAIL_CACHE_BACKEND = "default"
WAGTAIL_CACHE_HEADER = "X-Wagtail-Cache"
WAGTAIL_CACHE_IGNORE_COOKIES = True
WAGTAIL_CACHE_MAX_AGE = 5 * 60
WAGTAIL_CACHE_IGNORE_QS = [
r"^_bta_.*$", # Bronto
r"^_ga$", # Google Analytics
Expand Down
6 changes: 5 additions & 1 deletion wagtailcache/templates/wagtailcache/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ <h2>{% trans "Status" %}</h2>
<b>{% trans "ENABLED" %}</b>
</p>
<p>
{% trans "Cached pages are automatically refreshed every" %} <b>{% cache_timeout %}</b>.<br>
{% if cache_timeout == None %}
{% trans "Cached pages do not expire." %}<br>
{% else %}
{% trans "Cached pages are automatically refreshed every" %} <b>{{ cache_timeout|seconds_to_readable }}</b>.<br>
{% endif %}
{% trans "To modify this, change the <code>TIMEOUT</code> value of the cache backend in the project settings." %}
</p>
<p>
Expand Down
13 changes: 1 addition & 12 deletions wagtailcache/templatetags/wagtailcache_tags.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Optional

from django import template
from django.core.cache import caches
from django.utils.translation import gettext_lazy as _

from wagtailcache.settings import wagtailcache_settings
Expand All @@ -10,6 +9,7 @@
register = template.Library()


@register.filter
def seconds_to_readable(seconds: int) -> str:
"""
Converts int seconds to a human readable string.
Expand Down Expand Up @@ -43,14 +43,3 @@ def get_wagtailcache_setting(value: str) -> Optional[object]:
Returns a wagtailcache Django setting, or default.
"""
return getattr(wagtailcache_settings, value, None)


@register.simple_tag
def cache_timeout() -> str:
"""
Returns the wagtailcache timeout in human readable format.
"""
timeout = caches[
wagtailcache_settings.WAGTAIL_CACHE_BACKEND
].default_timeout
return seconds_to_readable(timeout)
3 changes: 3 additions & 0 deletions wagtailcache/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ def index(request):
"wagtailcache/index.html",
{
"keyring": keyring,
"cache_timeout": caches[
wagtailcache_settings.WAGTAIL_CACHE_BACKEND
].default_timeout,
},
)

Expand Down