- 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
- Mask sensitive data from logger by agusmakmun 1 week, 5 days ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 2 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 2 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 9 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 10 months ago
Comments
Please login first before commenting.