Login

Cache Backend using memcached including prefix settings

Author:
mojemeno123
Posted:
June 27, 2012
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Django later than 1.3 (not sure of exact version) wasn't using prefix settings in cache tags or functions used in views. Just for whole page caching. This is small custom cache snippet based on memcached.CacheClass. Feel free adding any comments.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.