1. Sylvain Hellegouarch
  2. CherryPy Recipes

Source

CherryPy Recipes / web / caching / redis_caching / redisplugin.py

# -*- coding: utf-8 -*-
import cherrypy
from cherrypy.process import plugins
import redis

__all__ = ['RedisPlugin']

class RedisPlugin(plugins.SimplePlugin):
    def __init__(self, bus, host='127.0.0.1', port=6379):
        plugins.SimplePlugin.__init__(self, bus)
        self.client = redis.StrictRedis(host=host, port=port, db=0)

    def start(self):
        """ Add the channels dedicated to the
        caching API to the bus.
        """
        self.bus.log('Setting up the redis 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 redis 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)