Created
March 30, 2010 22:38
-
-
Save eculver/349692 to your computer and use it in GitHub Desktop.
Simple Django cache backend overrides for dealing with python-memcached differences between cmemcache.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.core.cache.backends import memcached | |
from django.utils.encoding import smart_str | |
""" | |
Simple Django cache backend overrides for dealing with python-memcached | |
differences between cmemcache. | |
For Django 1.2. All methods except `set_many` and `delete_many` will work for Django 1.1 | |
Use by pointing to it in settings, for example: | |
CACHE_BACKEND = myproject.contrib.thisfile://127.0.0.1:11211 | |
""" | |
class CacheClass(memcached.CacheClass): | |
"Filter key through `_smart_key` before sending to backend for all cases" | |
def __init__(self, server, params): | |
super(CacheClass,self).__init__(server, params) | |
def add(self, key, value, timeout=0): | |
return super(CacheClass, self).add(self._smart_key(key), value, timeout) | |
def get(self, key): | |
return super(CacheClass, self).get(self._smart_key(key)) | |
def set(self, key, value, timeout=0): | |
super(CacheClass, self).set(self._smart_key(key), value, timeout) | |
def delete(self, key): | |
super(CacheClass, self).delete(self._smart_key(key)) | |
def _smart_key(self, key): | |
"Truncate all keys to 250 or less and remove control characters" | |
return smart_str(''.join([c for c in key | |
if ord(c) > 32 and ord(c) != 127]))[:250] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment