Skip to content

Instantly share code, notes, and snippets.

@jorenham
Last active October 22, 2021 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorenham/d81cfbcb655d965558b009257a16a1e8 to your computer and use it in GitHub Desktop.
Save jorenham/d81cfbcb655d965558b009257a16a1e8 to your computer and use it in GitHub Desktop.
Temporarily disable django caching
import contextlib
from typing import ContextManager
from django.core import cache
from django.core.cache.backends.dummy import DummyCache
@contextlib.contextmanager
def disable_caches(*aliases: str) -> ContextManager[tuple[str, ...]]:
"""Temporarily disable django caching backends. By default, all connected
caching backends are disabled.
This is a Django 3+ compatible variant of:
https://gist.github.com/kaedroho/cefd778ff5ea85166ded1ef817c62c6d
"""
# noinspection PyUnresolvedReferences,PyProtectedMember
cache_settings, cons = cache.caches.settings, cache.caches._connections
aliases = list(aliases or cache_settings)
caches_old = {
k: cache.caches[k] for k in aliases
if hasattr(cons, k) and not isinstance(cache.caches[k], DummyCache)
}
for alias in caches_old:
params = cache_settings[alias].copy()
params.pop('BACKEND')
location = params.pop('LOCATION', '')
cache_tmp = DummyCache(location, params)
setattr(cons, alias, cache_tmp)
try:
yield tuple(caches_old)
finally:
for alias, cache_old in caches_old.items():
setattr(cons, alias, cache_old)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment