PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/django-1.2/django/core/cache/backends/memcached.py

https://github.com/theosp/google_appengine
Python | 104 lines | 69 code | 19 blank | 16 comment | 15 complexity | ed0f34a46de4e50c9fa968bbdd181b38 MD5 | raw file
  1. "Memcached cache backend"
  2. import time
  3. from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
  4. from django.utils.encoding import smart_unicode, smart_str
  5. try:
  6. import cmemcache as memcache
  7. import warnings
  8. warnings.warn(
  9. "Support for the 'cmemcache' library has been deprecated. Please use python-memcached instead.",
  10. PendingDeprecationWarning
  11. )
  12. except ImportError:
  13. try:
  14. import memcache
  15. except:
  16. raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library")
  17. class CacheClass(BaseCache):
  18. def __init__(self, server, params):
  19. BaseCache.__init__(self, params)
  20. self._cache = memcache.Client(server.split(';'))
  21. def _get_memcache_timeout(self, timeout):
  22. """
  23. Memcached deals with long (> 30 days) timeouts in a special
  24. way. Call this function to obtain a safe value for your timeout.
  25. """
  26. timeout = timeout or self.default_timeout
  27. if timeout > 2592000: # 60*60*24*30, 30 days
  28. # See http://code.google.com/p/memcached/wiki/FAQ
  29. # "You can set expire times up to 30 days in the future. After that
  30. # memcached interprets it as a date, and will expire the item after
  31. # said date. This is a simple (but obscure) mechanic."
  32. #
  33. # This means that we have to switch to absolute timestamps.
  34. timeout += int(time.time())
  35. return timeout
  36. def add(self, key, value, timeout=0):
  37. if isinstance(value, unicode):
  38. value = value.encode('utf-8')
  39. return self._cache.add(smart_str(key), value, self._get_memcache_timeout(timeout))
  40. def get(self, key, default=None):
  41. val = self._cache.get(smart_str(key))
  42. if val is None:
  43. return default
  44. return val
  45. def set(self, key, value, timeout=0):
  46. self._cache.set(smart_str(key), value, self._get_memcache_timeout(timeout))
  47. def delete(self, key):
  48. self._cache.delete(smart_str(key))
  49. def get_many(self, keys):
  50. return self._cache.get_multi(map(smart_str,keys))
  51. def close(self, **kwargs):
  52. self._cache.disconnect_all()
  53. def incr(self, key, delta=1):
  54. try:
  55. val = self._cache.incr(key, delta)
  56. # python-memcache responds to incr on non-existent keys by
  57. # raising a ValueError. Cmemcache returns None. In both
  58. # cases, we should raise a ValueError though.
  59. except ValueError:
  60. val = None
  61. if val is None:
  62. raise ValueError("Key '%s' not found" % key)
  63. return val
  64. def decr(self, key, delta=1):
  65. try:
  66. val = self._cache.decr(key, delta)
  67. # python-memcache responds to decr on non-existent keys by
  68. # raising a ValueError. Cmemcache returns None. In both
  69. # cases, we should raise a ValueError though.
  70. except ValueError:
  71. val = None
  72. if val is None:
  73. raise ValueError("Key '%s' not found" % key)
  74. return val
  75. def set_many(self, data, timeout=0):
  76. safe_data = {}
  77. for key, value in data.items():
  78. if isinstance(value, unicode):
  79. value = value.encode('utf-8')
  80. safe_data[smart_str(key)] = value
  81. self._cache.set_multi(safe_data, self._get_memcache_timeout(timeout))
  82. def delete_many(self, keys):
  83. self._cache.delete_multi(map(smart_str, keys))
  84. def clear(self):
  85. self._cache.flush_all()