cache.py 1.4 KB

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