Created
November 28, 2022 17:27
-
-
Save cnk/a9b290e636c004fc5b4bcc4528c5958f to your computer and use it in GitHub Desktop.
Controlling caching by overriding serve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.template.response import TemplateResponse | |
from wagtail.core.models import Page, PageViewRestriction | |
DEFAULT_PAGE_CACHE_TIME = 60 * 5 # 5 minutes | |
class BasePage(Page): | |
""" | |
This model contains methods we want added to all (or nearly all) of our custom Page types. Right | |
now that is our Cache-Control headers. The values for these are a work in progress and for now | |
are basically either saying "don't cache locally or on Cloudflare" OR "please cache on | |
Cloudflare". I am not setting a browser cache time because it makes it harder for me to test | |
rules. And I am using the more general "CDN-Cache-Control" header so I can see that the value is | |
getting served. When I use "Cloudflare-CDN-Cache-Control" the header gets stripped so I can't be | |
100% sure that it got served and what value it had. | |
""" | |
def is_private(self): | |
restricted_pages = PageViewRestriction.objects.values('page_id') | |
return self.get_ancestors(inclusive=True).filter(id__in=restricted_pages).exists() | |
def cache_control_headers(self, request): | |
request.is_preview = getattr(request, 'is_preview', False) | |
if request.is_preview or self.is_private(): | |
return {"Cache-Control": "private, max-age=0, s-maxage=0"} | |
else: | |
return {"CDN-Cache-Control": f"public, max-age={DEFAULT_PAGE_CACHE_TIME}"} | |
def serve(self, request, *args, **kwargs): | |
""" | |
This is essentially a monkey patch of Wagtail's Page.serve() method. | |
It's here to set Cache-Control headers depending on page privacy. | |
""" | |
request.is_preview = getattr(request, 'is_preview', False) | |
return TemplateResponse( | |
request, | |
self.get_template(request, *args, **kwargs), | |
self.get_context(request, *args, **kwargs), | |
headers=self.cache_control_headers(request), | |
) | |
class Meta: | |
abstract = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment