Source

heechee / heechee / webdav / caching / memcached.py

Full commit
import logging

try:
    import cmemcache as memcache
except ImportError:
    import memcache

try:
    from hashlib import md5
except ImportError:
    from md5 import md5

class MemcachedCache(object):
    """
    Simple memcache cache.
    """    
    def __init__(self, servers, timeout=600):
        """
        Constructor. 'servers' is a LIST of servers to connect to.
        """
        self._cache = memcache.Client(servers)
        self.timeout = timeout
    
    def __getitem__(self, key):
        value = self._cache.get(key)
        if value is not None:
            logging.debug("cache HIT: %r" % key)
            return value
        else:
            logging.debug("cache MISS: %r" % key)
            raise KeyError("No such key %r" % key)
    
    def __setitem__(self, key, value):
        logging.debug("cache SET: %r (%i)" % (key, len(value)))
        self._cache.add(key, value, self.timeout)