# -*- coding: utf-8 -*- # !/usr/bin/env python import logging import threading from django.core.cache import CacheHandler, _create_cache, InvalidCacheBackendError logger = logging.getLogger(__name__) _getitem = CacheHandler.__getitem__ def patch_cache_handler(): CacheHandler._poll_cache_lock = threading.Lock() def __getitem__(self, alias): from django.conf import settings if alias not in settings.CACHES: raise InvalidCacheBackendError( "Could not find config for '%s' in settings.CACHES" % alias ) if settings.CACHES[alias].get('BACKEND_TYPE', '') == 'pool': try: return self._poll_caches[alias] except AttributeError: pass except KeyError: pass with self._poll_cache_lock: logger.debug('init cache poll'.format(alias)) if getattr(self, '_poll_caches', None) is None: self._poll_caches = {} cache = _create_cache(alias) self._poll_caches[alias] = cache return cache else: return _getitem(self, alias) CacheHandler.__getitem__ = __getitem__ patch_cache_handler()