diff --git a/common/cloudflare.py b/common/cloudflare.py index 28124815..6851c5c9 100644 --- a/common/cloudflare.py +++ b/common/cloudflare.py @@ -60,9 +60,7 @@ def purge_paths_cache(cls, paths): apiUrl = f"https://api.cloudflare.com/client/v4/zones/{zoneId}/purge_cache" # Absolute URLs - domain = Site.objects.get_current().domain - rcvisUrls = [f'https://{domain}{path}' for path in paths] - data = {'files': rcvisUrls} + data = {'files': get_purge_paths_for(paths)} # Send it off response = requests.post( @@ -76,3 +74,11 @@ def purge_paths_cache(cls, paths): logger.info("Cleared cloudflare cache for %s: %s", info, response.json()) else: logger.error("Received bad response from cloudflare for %s: %s", info, response.json()) + + @classmethod + def get_purge_paths_for(cls, paths): + domain = Site.objects.get_current().domain + rcvisUrls = [f'https://{domain}{path}' for path in paths] + if not domain.startswith("www"): + rcvisUrls.extend([f'https://www.{domain}{path}' for path in paths]) + return rcvisUrls diff --git a/visualizer/tests/testRestApi.py b/visualizer/tests/testRestApi.py index 44d58658..09569474 100644 --- a/visualizer/tests/testRestApi.py +++ b/visualizer/tests/testRestApi.py @@ -8,12 +8,14 @@ from mock import patch from django.contrib.auth import get_user_model +from django.contrib.sites.models import Site from django.core.cache import cache from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from rest_framework_tracking.models import APIRequestLog +from common.cloudflare import CloudflareAPI from common.testUtils import TestHelpers from visualizer.tests import filenames @@ -424,3 +426,12 @@ def test_update_clears_cloudflare_cache(self, purgeMock): # Ensure purge is called once edited purgeMock.assert_called_once() + purgeMock.assert_called_with('one-round') + + def test_purge_paths(self): + """ Test that cloudflare cache clears both www and non-www addresses """ + paths = CloudflareAPI.get_purge_paths_for('/v/one-round') + firstPath = paths[0] + firstPathWithWWW = firstPath.replace("://", "://www.") + self.assertNotIn('www', Site.objects.get_current().domain) + self.assertIn(firstPathWithWWW, paths)