Make cache lazy to allow test runners to switch cache backends
|Reported by:||brianjaystanley||Owned by:||nobody|
|Component:||Core (Cache system)||Version:||1.3|
|Cc:||zimnyx@…, brianjaystanley||Triage Stage:||Design decision needed|
|Has patch:||yes||Needs documentation:||yes|
|Needs tests:||yes||Patch needs improvement:||no|
django.core.cache.cache is currently a module-level variable that references an instance of the default cache backend from settings.CACHES. Loading the cache backend into a module-level variable makes it difficult to switch to a different cache backend at runtime. Switching cache backends at runtime would be useful in test runners, in order to be able to test caching-related functionality without populating a production cache. settings.CACHES supports multiple caches, but the only way to use a cache other than the "default" is by calling get_cache, but then only the caller has the reference to the new cache backend while other modules (including the cache-based session backends) will continue to use the default cache backend referenced by django.core.cache.cache.
The patch wraps the cache variable in SimpleLazyObject. This allows doing something like this in a test runner:
cache._wrapped = get_cache('test')
This doesn't break anything in the Django test suite.
Change History (6)
comment:1 Changed 5 years ago by
|Patch needs improvement:||unset|
comment:2 Changed 5 years ago by
|Triage Stage:||Unreviewed → Design decision needed|