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. Image compression before saving the new model / work with JPG, PNG by Schleidens 2 weeks, 2 days ago
  2. Help text hyperlinks by sa2812 1 month, 1 week ago
  3. Stuff by NixonDash 3 months, 2 weeks ago
  4. Add custom fields to the built-in Group model by jmoppel 5 months, 3 weeks ago
  5. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 9 months ago

Comments

Please login first before commenting.