Created
July 6, 2011 16:17
-
-
Save diox/1067644 to your computer and use it in GitHub Desktop.
Custom memcached backends for django, enabling binary protocol and hiding errors
This file contains hidden or 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 | |
import pylibmc | |
import logging | |
log = logging.getLogger('django.core.cache.backends.memcached') | |
class BinaryPyLibMCCache(memcached.PyLibMCCache): | |
""" | |
Custom cache backend using pylibmc that enables binary protocol | |
Note: inherits from django's PyLibMCCache, and most of the code is a | |
copy/paste from the django version, the only difference is the binary=True | |
argument to Client(). | |
""" | |
@property | |
def _cache(self): | |
# PylibMC uses cache options as the 'behaviors' attribute. | |
# It also needs to use threadlocals, because some versions of | |
# PylibMC don't play well with the GIL. | |
client = getattr(self._local, 'client', None) | |
if client: | |
return client | |
client = self._lib.Client(self._servers, binary=True) | |
if self._options: | |
client.behaviors = self._options | |
self._local.client = client | |
return client | |
class SilentPyLibMCCache(object): | |
def __init__(self, *args, **kwargs): | |
self.instance = BinaryPyLibMCCache(*args, **kwargs) | |
def __getattr__(self, name): | |
if hasattr(self.instance, name): | |
func = getattr(self.instance, name) | |
return lambda *args, **kwargs: self._wrap(func, args, kwargs) | |
raise AttributeError(name) | |
def _wrap(self, func, args, kwargs): | |
try: | |
result = func(*args, **kwargs) | |
except pylibmc.errors, e: | |
result = None | |
log.warning('%s.%s error' % (self.instance.__class__.__name__, func.__name__), exc_info=True) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment