Refs #5815, #31938, #34271 -- Created invalidate_view_cache function to manually invalidate cache key.

Thanks Laurent Tramoy for the implementation idea and Carlton Gibson for
the support.
This commit is contained in:
Ramiro Juan Nocelli 2025-10-11 19:06:31 +02:00
parent 6e3287408e
commit 20e26762ec
2 changed files with 87 additions and 6 deletions

38
tests/cache/tests.py vendored
View file

@ -57,6 +57,7 @@ from django.test.utils import CaptureQueriesContext
from django.utils import timezone, translation
from django.utils.cache import (
get_cache_key,
invalidate_view_cache,
learn_cache_key,
patch_cache_control,
patch_vary_headers,
@ -2625,6 +2626,43 @@ class CacheMiddlewareTest(SimpleTestCase):
self.assertIsNotNone(result)
self.assertEqual(result.content, b"Hello World 1")
def test_invalidate_view_decorator_cache_from_request(self):
"""Invalidate cache key/value from request object"""
view = cache_page(10)(hello_world_view)
request = self.factory.get("/view/")
_ = view(request, "0")
cache_key = get_cache_key(request=request, key_prefix="", ignore_headers=True)
cached_response = cache.get(cache_key)
# Verify request.content has been chached
self.assertEqual(cached_response.content, b"Hello World 0")
# Delete cache key/value
invalidate_view_cache(request=request, key_prefix="")
cached_response = cache.get(cache_key)
# Confirm key/value has been deleted from cache
self.assertIsNone(cached_response)
def test_invalidate_view_decorator_cache_from_path(self):
"""Invalidate cache key/value from path"""
view = cache_page(10)(hello_world_view)
path = "/view/"
request = self.factory.get(path)
_ = view(request, "0")
cache_key = get_cache_key(request=request, key_prefix="", ignore_headers=True)
cached_response = cache.get(cache_key)
# Verify request.content has been chached
self.assertEqual(cached_response.content, b"Hello World 0")
# Delete cache key/value
invalidate_view_cache(path=path, key_prefix="")
cached_response = cache.get(cache_key)
# Confirm key/value has been deleted from cache
self.assertIsNone(cached_response)
def test_view_decorator(self):
# decorate the same view with different cache decorators
default_view = cache_page(3)(hello_world_view)