__init__.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import logging
  4. import threading
  5. from django.core.cache import CacheHandler, _create_cache, InvalidCacheBackendError
  6. logger = logging.getLogger(__name__)
  7. _getitem = CacheHandler.__getitem__
  8. def patch_cache_handler():
  9. CacheHandler._poll_cache_lock = threading.Lock()
  10. def __getitem__(self, alias):
  11. from django.conf import settings
  12. if alias not in settings.CACHES:
  13. raise InvalidCacheBackendError(
  14. "Could not find config for '%s' in settings.CACHES" % alias
  15. )
  16. if settings.CACHES[alias].get('BACKEND_TYPE', '') == 'pool':
  17. try:
  18. return self._poll_caches[alias]
  19. except AttributeError:
  20. pass
  21. except KeyError:
  22. pass
  23. with self._poll_cache_lock:
  24. logger.debug('init cache poll<alias={}>'.format(alias))
  25. if getattr(self, '_poll_caches', None) is None:
  26. self._poll_caches = {}
  27. cache = _create_cache(alias)
  28. self._poll_caches[alias] = cache
  29. return cache
  30. else:
  31. return _getitem(self, alias)
  32. CacheHandler.__getitem__ = __getitem__
  33. patch_cache_handler()