diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py index b97c7469bb..346deae916 100644 --- a/django/core/cache/__init__.py +++ b/django/core/cache/__init__.py @@ -176,12 +176,13 @@ def get_cache(backend, **kwargs): except (AttributeError, ImportError), e: raise InvalidCacheBackendError( "Could not find backend '%s': %s" % (backend, e)) - return backend_cls(location, params) + cache = backend_cls(location, params) + # Some caches -- python-memcached in particular -- need to do a cleanup at the + # end of a request cycle. If the cache provides a close() method, wire it up + # here. + if hasattr(cache, 'close'): + signals.request_finished.connect(cache.close) + return cache cache = get_cache(DEFAULT_CACHE_ALIAS) -# Some caches -- python-memcached in particular -- need to do a cleanup at the -# end of a request cycle. If the cache provides a close() method, wire it up -# here. -if hasattr(cache, 'close'): - signals.request_finished.connect(cache.close) diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py index 0e28f66ae8..bd29cde533 100644 --- a/tests/regressiontests/cache/tests.py +++ b/tests/regressiontests/cache/tests.py @@ -1040,6 +1040,13 @@ class GetCacheTests(unittest.TestCase): self.assertRaises(InvalidCacheBackendError, get_cache, 'does_not_exist') + def test_close(self): + from django.core import signals + cache = get_cache('regressiontests.cache.closeable_cache.CacheClass') + self.assertFalse(cache.closed) + signals.request_finished.send(self.__class__) + self.assertTrue(cache.closed) + class CacheUtils(TestCase): """TestCase for django.utils.cache functions."""