1
0
mirror of https://github.com/django/django.git synced 2024-12-22 09:05:43 +00:00

Fixed #33252 -- Made cache middlewares thread-safe.

This commit is contained in:
Iuri de Silvio 2021-10-31 21:54:13 -03:00 committed by Mariusz Felisiak
parent 0c05c183e4
commit 3ff7b15bb7
2 changed files with 23 additions and 3 deletions

View File

@ -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

15
tests/cache/tests.py vendored
View File

@ -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',