cache.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """celery.backends.cache"""
  2. from django.utils.encoding import smart_str
  3. from django.core.cache import cache, get_cache
  4. from django.core.cache.backends.base import InvalidCacheBackendError
  5. from celery import conf
  6. from celery.backends.base import KeyValueStoreBackend
  7. # CELERY_CACHE_BACKEND overrides the django-global(tm) backend settings.
  8. if conf.CELERY_CACHE_BACKEND:
  9. cache = get_cache(conf.CELERY_CACHE_BACKEND)
  10. class DjangoMemcacheWrapper(object):
  11. """Wrapper class to django's memcache backend class, that overrides the
  12. :meth:`get` method in order to remove the forcing of unicode strings
  13. since it may cause binary or pickled data to break."""
  14. def __init__(self, cache):
  15. self.cache = cache
  16. def get(self, key, default=None):
  17. val = self.cache._cache.get(smart_str(key))
  18. if val is None:
  19. return default
  20. else:
  21. return val
  22. def set(self, key, value, timeout=0):
  23. self.cache.set(key, value, timeout)
  24. # Check if django is using memcache as the cache backend. If so, wrap the
  25. # cache object in a DjangoMemcacheWrapper that fixes a bug with retrieving
  26. # pickled data
  27. from django.core.cache.backends.memcached import CacheClass
  28. if isinstance(cache, CacheClass):
  29. cache = DjangoMemcacheWrapper(cache)
  30. class CacheBackend(KeyValueStoreBackend):
  31. """Backend using the Django cache framework to store task metadata."""
  32. def get(self, key):
  33. return cache.get(key)
  34. def set(self, key, value):
  35. cache.set(key, value)