Cache Backend using memcached including prefix settings

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"Custom cache backend"
# Add following to your settings.py
# ------------
# settings same as for memcached
# CACHE_BACKEND = 'custom_cache://127.0.0.1:11211/'
# CACHE_MIDDLEWARE_KEY_PREFIX = 'site_prefix_'

from django.core.cache.backends import memcached
from django.utils.encoding import smart_unicode, smart_str
from django.conf import settings

class CacheClass(memcached.CacheClass):
    def __init__(self, server, params):
        super(CacheClass, self).__init__(server, params)
        self._prefix = getattr(settings, "CACHE_MIDDLEWARE_KEY_PREFIX", "")
        
    def _key(self, key, is_list=False):
        if is_list:
            keys = []
            for k in key:
                keys.append("%s%s" % (self._prefix, k))
            return keys
        else:
            return "%s%s" % (self._prefix, key)

    def add(self, key, value, timeout=0):
        return super(CacheClass, self).add(self._key(key), value, timeout)

    def get(self, key, default=None):
        return super(CacheClass, self).get(self._key(key), default)

    def set(self, key, value, timeout=0):
        super(CacheClass, self).set(self._key(key), value, timeout)

    def delete(self, key):
        super(CacheClass, self).delete(self._key(key))

    def get_many(self, keys):
        return super(CacheClass, self).get_many(self._key(keys, True))

    def close(self, **kwargs):
        super(CacheClass, self).close(**kwargs)

    def incr(self, key, delta=1):
        return super(CacheClass, self).incr(self._key(key), delta)

    def decr(self, key, delta=1):
        return super(CacheClass, self).decr(self._key(key), delta)

More like this

  1. Property Attributes in Memcache by ori 2 years, 5 months ago
  2. JSON instead of pickle for memcached by diverman 2 years, 3 months ago
  3. clear cache view by zodman 1 year, 4 months ago
  4. Another Memcache Status View by cmheisel 6 years, 2 months ago
  5. Scoped Cache Compatible with Django Caching Helpers by axiak 6 years, 1 month ago

Comments

(Forgotten your password?)