Skip to content

Instantly share code, notes, and snippets.

@gciotta
Created June 15, 2010 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gciotta/439868 to your computer and use it in GitHub Desktop.
Save gciotta/439868 to your computer and use it in GitHub Desktop.
from django.conf import settings
from django.core.cache import get_cache
from django.core.cache.backends.base import BaseCache
from django.contrib.sites.models import Site
from django.utils.encoding import smart_str
class CacheClass(BaseCache):
'''A wrapper around the django cache.
It adds a prefix to cache keys, useful to avoid key clashes on shared stores
(e.g. a shared memcache instance). The prefix is omitted if the key starts
with the current site domain. This is useful when the data are exposed to
externals clients without depending on any specific key prefix.
Example configuration in ``settings.py``::
CACHE_WRAPPED_BACKEND = 'memcached://192.168.1.3:11211?timeout=%(two_days)s' % {'two_days':60*60*24*2}
CACHE_BACKEND = 'lib.cache.prefixed_cache://community_DEVEL_%(node)s' % {'node':platform.node()}
'''
def __init__(self, key_prefix, *args, **kwargs):
self.key_prefix = smart_str(key_prefix)
self.wrapped_backend = get_cache(settings.CACHE_WRAPPED_BACKEND)
super(CacheClass, self).__init__(*args, **kwargs)
def get_many(self, keys, *args, **kwargs):
key_prefix = self.key_prefix
current_domain = Site.objects.get_current().domain
multi_key = ['%s_%s' % (key_prefix, smart_str(key)) if not
key.startswith(current_domain) else key for key in keys]
prefix_len = len(key_prefix) + 1 # +1 for the '_'
return dict((k[prefix_len:], v) for k,v in
self.wrapped_backend.get_many(multi_key, *args, **kwargs).iteritems())
def _cache_wrapper_factory(func_name):
def wrapper(self, key, *args, **kwds):
# omit prefix if the key starts with the current site domain.
if not key.startswith(Site.objects.get_current().domain):
key = '%s_%s' % (self.key_prefix, smart_str(key))
return getattr(self.wrapped_backend, func_name)(key, *args, **kwds)
wrapper.__name__ = func_name
return wrapper
for name in 'add get set incr delete has_key __contains__'.split():
assert hasattr(CacheClass, name), 'CacheClass.%s does not exist (typo?)'%name
setattr(CacheClass, name, _cache_wrapper_factory(name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment