frontendcache.rst 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. .. _frontend_cache_purging:
  2. Frontend cache invalidator
  3. ==========================
  4. Many websites use a frontend cache such as Varnish, Squid, Cloudflare or CloudFront to gain extra performance. The downside of using a frontend cache though is that they don't respond well to updating content and will often keep an old version of a page cached after it has been updated.
  5. This document describes how to configure Wagtail to purge old versions of pages from a frontend cache whenever a page gets updated.
  6. Setting it up
  7. -------------
  8. Firstly, add ``"wagtail.contrib.frontend_cache"`` to your INSTALLED_APPS:
  9. .. code-block:: python
  10. INSTALLED_APPS = [
  11. ...
  12. "wagtail.contrib.frontend_cache"
  13. ]
  14. The ``wagtailfrontendcache`` module provides a set of signal handlers which will automatically purge the cache whenever a page is published or deleted. These signal handlers are automatically registered when the ``wagtail.contrib.frontend_cache`` app is loaded.
  15. Varnish/Squid
  16. ^^^^^^^^^^^^^
  17. Add a new item into the ``WAGTAILFRONTENDCACHE`` setting and set the ``BACKEND`` parameter to ``wagtail.contrib.frontend_cache.backends.HTTPBackend``. This backend requires an extra parameter ``LOCATION`` which points to where the cache is running (this must be a direct connection to the server and cannot go through another proxy).
  18. .. code-block:: python
  19. # settings.py
  20. WAGTAILFRONTENDCACHE = {
  21. 'varnish': {
  22. 'BACKEND': 'wagtail.contrib.frontend_cache.backends.HTTPBackend',
  23. 'LOCATION': 'http://localhost:8000',
  24. },
  25. }
  26. WAGTAILFRONTENDCACHE_LANGUAGES = []
  27. Set ``WAGTAILFRONTENDCACHE_LANGUAGES`` to a list of languages (typically equal to ``[l[0] for l in settings.LANGUAGES]``) to also purge the urls for each language of a purging url. This setting needs ``settings.USE_I18N`` to be ``True`` to work. Its default is an empty list.
  28. Finally, make sure you have configured your frontend cache to accept PURGE requests:
  29. - `Varnish <https://www.varnish-cache.org/docs/3.0/tutorial/purging.html>`_
  30. - `Squid <https://wiki.squid-cache.org/SquidFaq/OperatingSquid#How_can_I_purge_an_object_from_my_cache.3F>`_
  31. .. _frontendcache_cloudflare:
  32. Cloudflare
  33. ^^^^^^^^^^
  34. Firstly, you need to register an account with Cloudflare if you haven't already got one. You can do this here: `Cloudflare Sign up <https://www.cloudflare.com/sign-up>`_
  35. Add an item into the ``WAGTAILFRONTENDCACHE`` and set the ``BACKEND`` parameter to ``wagtail.contrib.frontend_cache.backends.CloudflareBackend``. This backend requires three extra parameters, ``EMAIL`` (your Cloudflare account email), ``TOKEN`` (your API token from Cloudflare), and ``ZONEID`` (for zone id for your domain, see below).
  36. To find the ``ZONEID`` for your domain, read the `Cloudflare API Documentation <https://api.cloudflare.com/#getting-started-resource-ids>`_
  37. .. code-block:: python
  38. # settings.py
  39. WAGTAILFRONTENDCACHE = {
  40. 'cloudflare': {
  41. 'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
  42. 'EMAIL': 'your-cloudflare-email-address@example.com',
  43. 'TOKEN': 'your cloudflare api token',
  44. 'ZONEID': 'your cloudflare domain zone id',
  45. },
  46. }
  47. .. _frontendcache_aws_cloudfront:
  48. Amazon CloudFront
  49. ^^^^^^^^^^^^^^^^^
  50. Within Amazon Web Services you will need at least one CloudFront web distribution. If you don't have one, you can get one here: `CloudFront getting started <https://aws.amazon.com/cloudfront/>`_
  51. Add an item into the ``WAGTAILFRONTENDCACHE`` and set the ``BACKEND`` parameter to ``wagtail.contrib.frontend_cache.backends.CloudfrontBackend``. This backend requires one extra parameter, ``DISTRIBUTION_ID`` (your CloudFront generated distribution id).
  52. .. code-block:: python
  53. WAGTAILFRONTENDCACHE = {
  54. 'cloudfront': {
  55. 'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudfrontBackend',
  56. 'DISTRIBUTION_ID': 'your-distribution-id',
  57. },
  58. }
  59. Configuration of credentials can done in multiple ways. You won't need to store them in your Django settings file. You can read more about this here: `Boto 3 Docs <https://boto3.readthedocs.org/en/latest/guide/configuration.html>`_
  60. In case you run multiple sites with Wagtail and each site has its CloudFront distribution, provide a mapping instead of a single distribution. Make sure the mapping matches with the hostnames provided in your site settings.
  61. .. code-block:: python
  62. WAGTAILFRONTENDCACHE = {
  63. 'cloudfront': {
  64. 'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudfrontBackend',
  65. 'DISTRIBUTION_ID': {
  66. 'www.wagtail.io': 'your-distribution-id',
  67. 'www.madewithwagtail.org': 'your-distribution-id',
  68. },
  69. },
  70. }
  71. .. note::
  72. In most cases, absolute URLs with ``www`` prefixed domain names should be used in your mapping. Only drop the ``www`` prefix if you're absolutely sure you're not using it (e.g. a subdomain).
  73. Advanced usage
  74. --------------
  75. Invalidating more than one URL per page
  76. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  77. By default, Wagtail will only purge one URL per page. If your page has more than one URL to be purged, you will need to override the ``get_cached_paths`` method on your page type.
  78. .. code-block:: python
  79. class BlogIndexPage(Page):
  80. def get_blog_items(self):
  81. # This returns a Django paginator of blog items in this section
  82. return Paginator(self.get_children().live().type(BlogPage), 10)
  83. def get_cached_paths(self):
  84. # Yield the main URL
  85. yield '/'
  86. # Yield one URL per page in the paginator to make sure all pages are purged
  87. for page_number in range(1, self.get_blog_items().num_pages + 1):
  88. yield '/?page=' + str(page_number)
  89. Invalidating index pages
  90. ^^^^^^^^^^^^^^^^^^^^^^^^
  91. Pages that list other pages (such as a blog index) may need to be purged as
  92. well so any changes to a blog page are also reflected on the index (for example,
  93. a blog post was added, deleted or its title/thumbnail was changed).
  94. To purge these pages, we need to write a signal handler that listens for
  95. Wagtail's ``page_published`` and ``page_unpublished`` signals for blog pages
  96. (note, ``page_published`` is called both when a page is created and updated).
  97. This signal handler would trigger the invalidation of the index page using the
  98. ``PurgeBatch`` class which is used to construct and dispatch invalidation requests.
  99. .. code-block:: python
  100. # models.py
  101. from django.dispatch import receiver
  102. from django.db.models.signals import pre_delete
  103. from wagtail.core.signals import page_published
  104. from wagtail.contrib.frontend_cache.utils import PurgeBatch
  105. ...
  106. def blog_page_changed(blog_page):
  107. # Find all the live BlogIndexPages that contain this blog_page
  108. batch = PurgeBatch()
  109. for blog_index in BlogIndexPage.objects.live():
  110. if blog_page in blog_index.get_blog_items().object_list:
  111. batch.add_page(blog_index)
  112. # Purge all the blog indexes we found in a single request
  113. batch.purge()
  114. @receiver(page_published, sender=BlogPage)
  115. def blog_published_handler(instance):
  116. blog_page_changed(instance)
  117. @receiver(pre_delete, sender=BlogPage)
  118. def blog_deleted_handler(instance):
  119. blog_page_changed(instance)
  120. .. _frontend_cache_invalidating_urls:
  121. Invalidating URLs
  122. ^^^^^^^^^^^^^^^^^
  123. The ``PurgeBatch`` class provides a ``.add_url(url)`` and a ``.add_urls(urls)``
  124. for adding individual URLs to the purge batch.
  125. For example, this could be useful for purging a single page on a blog index:
  126. .. code-block:: python
  127. from wagtail.contrib.frontend_cache.utils import PurgeBatch
  128. # Purge the first page of the blog index
  129. batch = PurgeBatch()
  130. batch.add_url(blog_index.url + '?page=1')
  131. batch.purge()
  132. The ``PurgeBatch`` class
  133. ^^^^^^^^^^^^^^^^^^^^^^^^
  134. All of the methods available on ``PurgeBatch`` are listed below:
  135. .. automodule:: wagtail.contrib.frontend_cache.utils
  136. .. autoclass:: PurgeBatch
  137. .. automethod:: add_url
  138. .. automethod:: add_urls
  139. .. automethod:: add_page
  140. .. automethod:: add_pages
  141. .. automethod:: purge