1
0
mirror of https://github.com/django/django.git synced 2025-06-08 13:09:13 +00:00

Fixed #25782 – duplicate cache using CacheMiddleware and cache_page.

This commit is contained in:
wassef911 2024-07-06 21:00:10 +01:00
parent 7ba2a0db20
commit f04d3d4c0d
No known key found for this signature in database
GPG Key ID: A4166E2C2C794D2C
2 changed files with 44 additions and 0 deletions

View File

@ -121,6 +121,12 @@ class UpdateCacheMiddleware(MiddlewareMixin):
cache_key = learn_cache_key(
request, response, timeout, self.key_prefix, cache=self.cache
)
# check header for "x-successive-cache" to avoid multiple cache sets
# if not found, set it as key used
if response.has_header("x-successive-cache"):
return response
response["x-successive-cache"] = cache_key
if hasattr(response, "render") and callable(response.render):
response.add_post_render_callback(
lambda r: self.cache.set(cache_key, r, timeout)

38
tests/cache/tests.py vendored
View File

@ -2984,3 +2984,41 @@ class CacheHandlerTest(SimpleTestCase):
# .all() initializes all caches.
self.assertEqual(len(test_caches.all(initialized_only=True)), 2)
self.assertEqual(test_caches.all(), test_caches.all(initialized_only=True))
@override_settings(
CACHES={
"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},
"other": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "other",
},
},
)
class DuplicateCacheKey(TestCase):
def test_cache_page_conflict(self):
"""cache_page isn't causing duplicates with middlewares"""
@cache_page(3000, cache="other")
def test_view(request):
return HttpResponse(b"Hello, world")
request = RequestFactory().get("/view/")
cache_key = (
"views.decorators.cache.cache_page..GET."
"5b30bdb36b35025daf3570b18c3bb916.d41d8cd98f00b204e9800998ecf8427e.en"
)
self.assertEqual(caches["default"].has_key(cache_key), False)
self.assertEqual(caches["other"].has_key(cache_key), False)
UpdateCacheMiddleware(test_view)(request)
self.assertEqual(caches["other"].has_key(cache_key), True)
self.assertEqual(caches["default"].has_key(cache_key), False)
CacheMiddleware(test_view)(request)
self.assertEqual(caches["other"].has_key(cache_key), True)
self.assertEqual(caches["default"].has_key(cache_key), False)
response = test_view(request)
self.assertEqual(response.content, b"Hello, world")