|
| 1 | +import threading |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.core.cache import caches |
| 5 | +from django.core.exceptions import ImproperlyConfigured |
| 6 | +from large_image.cache_util.base import BaseCache |
| 7 | +from large_image.exceptions import TileCacheConfigurationError |
| 8 | + |
| 9 | + |
| 10 | +class DjangoCache(BaseCache): |
| 11 | + """Use Django cache as the backing cache for large-image.""" |
| 12 | + |
| 13 | + def __init__(self, cache, getsizeof=None): |
| 14 | + super().__init__(0, getsizeof=getsizeof) |
| 15 | + self._django_cache = cache |
| 16 | + |
| 17 | + def __repr__(self): # pragma: no cover |
| 18 | + return f'DjangoCache<{repr(self._django_cache._alias)}>' |
| 19 | + |
| 20 | + def __iter__(self): # pragma: no cover |
| 21 | + # return invalid iter |
| 22 | + return None |
| 23 | + |
| 24 | + def __len__(self): # pragma: no cover |
| 25 | + # return invalid length |
| 26 | + return -1 |
| 27 | + |
| 28 | + def __contains__(self, key): |
| 29 | + hashed_key = self._hashKey(key) |
| 30 | + return self._django_cache.__contains__(hashed_key) |
| 31 | + |
| 32 | + def __delitem__(self, key): |
| 33 | + hashed_key = self._hashKey(key) |
| 34 | + return self._django_cache.delete(hashed_key) |
| 35 | + |
| 36 | + def __getitem__(self, key): |
| 37 | + hashed_key = self._hashKey(key) |
| 38 | + value = self._django_cache.get(hashed_key) |
| 39 | + if value is None: |
| 40 | + return self.__missing__(key) |
| 41 | + return value |
| 42 | + |
| 43 | + def __setitem__(self, key, value): |
| 44 | + hashed_key = self._hashKey(key) |
| 45 | + # TODO: do we want to use `add` instead to add a key only if it doesn’t already exist |
| 46 | + return self._django_cache.set(hashed_key, value) |
| 47 | + |
| 48 | + @property |
| 49 | + def curritems(self): # pragma: no cover |
| 50 | + raise NotImplementedError |
| 51 | + |
| 52 | + @property |
| 53 | + def currsize(self): # pragma: no cover |
| 54 | + raise NotImplementedError |
| 55 | + |
| 56 | + @property |
| 57 | + def maxsize(self): # pragma: no cover |
| 58 | + raise NotImplementedError |
| 59 | + |
| 60 | + def clear(self): |
| 61 | + self._django_cache.clear() |
| 62 | + |
| 63 | + @staticmethod |
| 64 | + def getCache(): # noqa: N802 |
| 65 | + try: |
| 66 | + name = getattr(settings, 'LARGE_IMAGE_CACHE_NAME', 'default') |
| 67 | + dajngo_cache = caches[name] |
| 68 | + except ImproperlyConfigured: |
| 69 | + raise TileCacheConfigurationError |
| 70 | + cache_lock = threading.Lock() |
| 71 | + cache = DjangoCache(dajngo_cache) |
| 72 | + return cache, cache_lock |
0 commit comments