Cache fragments for longer, and clear when editing page

This commit is contained in:
Jake Howard 2022-10-04 20:14:26 +01:00
parent 9096bd4b0b
commit fa85c8ba80
Signed by: jake
GPG key ID: 57AFB45680EDD477
4 changed files with 33 additions and 3 deletions

View file

@ -1,6 +1,6 @@
{% load wagtailcore_tags humanize_tags cache util_tags %}
{% cache 600|jitter:60 "content-details" page.id request.is_preview %}
{% cache FRAGMENT_CACHE_TTL|jitter:FRAGMENT_CACHE_TTL_JITTER "content-details" page.id request.is_preview %}
<div class="content-details field is-grouped">
{% if page.date %}
<span class="icon-text">

View file

@ -13,7 +13,7 @@
<div>
<h2 class="title is-3"><a href="{% pageurl page %}">{{ page.title }}</a></h2>
{% include "common/content-details.html" %}
{% cache 900|jitter:60 "summary" page.id request.is_preview %}
{% cache FRAGMENT_CACHE_TTL|jitter:FRAGMENT_CACHE_TTL_JITTER "summary" page.id request.is_preview %}
<p>{{ page.summary }}</p>
{% endcache %}
</div>

View file

@ -0,0 +1,23 @@
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.http.request import HttpRequest
from wagtail import hooks
from wagtail.models import Page
from website.common.models import BasePage
FRAGMENT_CACHES = {"summary", "content-details"}
@hooks.register("after_edit_page")
def clear_fragment_cache(request: HttpRequest, page: Page) -> None:
if not isinstance(page, BasePage):
return
cache.delete_many(
[
# Empty string is for the empty value of `request.is_preview`
make_template_fragment_key(cache_name, [page.id, False])
for cache_name in FRAGMENT_CACHES
]
)

View file

@ -3,4 +3,11 @@ from django.http.request import HttpRequest
def global_vars(request: HttpRequest) -> dict:
return {"SEO_INDEX": settings.SEO_INDEX, "DEBUG": settings.DEBUG}
# noop caching in preview
fragment_cache_ttl = 0 if getattr(request, "is_preview", False) else 3600
return {
"SEO_INDEX": settings.SEO_INDEX,
"DEBUG": settings.DEBUG,
"FRAGMENT_CACHE_TTL": fragment_cache_ttl,
"FRAGMENT_CACHE_TTL_JITTER": fragment_cache_ttl * 0.1,
}