From 3ff7b15bb79f2ee5b7af245c55ae14546243bb77 Mon Sep 17 00:00:00 2001 From: Iuri de Silvio Date: Sun, 31 Oct 2021 21:54:13 -0300 Subject: [PATCH] Fixed #33252 -- Made cache middlewares thread-safe. --- django/middleware/cache.py | 11 ++++++++--- tests/cache/tests.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/django/middleware/cache.py b/django/middleware/cache.py index 85de0e91c5..c191118183 100644 --- a/django/middleware/cache.py +++ b/django/middleware/cache.py @@ -67,7 +67,10 @@ class UpdateCacheMiddleware(MiddlewareMixin): self.page_timeout = None self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS - self.cache = caches[self.cache_alias] + + @property + def cache(self): + return caches[self.cache_alias] def _should_update_cache(self, request, response): return hasattr(request, '_cache_update_cache') and request._cache_update_cache @@ -126,7 +129,10 @@ class FetchFromCacheMiddleware(MiddlewareMixin): super().__init__(get_response) self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS - self.cache = caches[self.cache_alias] + + @property + def cache(self): + return caches[self.cache_alias] def process_request(self, request): """ @@ -183,7 +189,6 @@ class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware): if cache_alias is None: cache_alias = DEFAULT_CACHE_ALIAS self.cache_alias = cache_alias - self.cache = caches[self.cache_alias] except KeyError: pass diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 13ff0a45aa..ddfe9ddfe6 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -2488,6 +2488,21 @@ class CacheMiddlewareTest(SimpleTestCase): self.assertIn('Cache-Control', response) self.assertIn('Expires', response) + def test_per_thread(self): + """The cache instance is different for each thread.""" + thread_caches = [] + middleware = CacheMiddleware(empty_response) + + def runner(): + thread_caches.append(middleware.cache) + + for _ in range(2): + thread = threading.Thread(target=runner) + thread.start() + thread.join() + + self.assertIsNot(thread_caches[0], thread_caches[1]) + @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',