CherryPy Recipes / web / caching / memcached_caching /

Full commit
# -*- coding: utf-8 -*-
import cherrypy
from cherrypy.process import plugins
from memcache import Client

__all__ = ['MemcachedPlugin']

class MemcachedPlugin(plugins.SimplePlugin):
    def __init__(self, bus, nodes=''):
        plugins.SimplePlugin.__init__(self, bus)
        if isinstance(nodes, basestring):
            nodes = [nodes]
        self.client = Client(nodes)

    def start(self):
        """ Add the channels dedicated to the
        caching API to the bus.
        self.bus.log('Setting up the memcached client')
        self.bus.subscribe("cache-value", self.cache)
        self.bus.subscribe("get-cached-value", self.get)
        self.bus.subscribe("del-cached-value", self.delete)

    def stop(self):
        """ Remove the channels dedicated to the
        caching API from the bus.
        self.bus.log('Releasing the memcached client')
        self.bus.unsubscribe("cache-value", self.cache)
        self.bus.unsubscribe("get-cached-value", self.get)
        self.bus.unsubscribe("del-cached-value", self.delete)
        self.client = None

    def cache(self, key, value):
        self.client.set(key, value)

    def get(self, key):
        return self.client.get(key)

    def delete(self, key):
        return self.client.delete(key)