Last active
October 22, 2021 15:29
-
-
Save jorenham/d81cfbcb655d965558b009257a16a1e8 to your computer and use it in GitHub Desktop.
Temporarily disable django caching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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