Caching HTTP Responses with CherryPy

The most basic case is very simple.

import time
import cherrypy
 
class WebSvc(object):
    @cherrypy.tools.caching(delay=300)
    @cherrypy.expose
    def quadruple(self, number):
        time.sleep(1) # make the real call somewhat costly
        return str(int(number) * 4)
 
cherrypy.quickstart(WebSvc())

That uses an in-memory cache and defaults to items expiring from the cache in 300 seconds (5 minutes). If you want to tweak that setting or others you can configure the caching tool to your liking.

cw

This is in response to a post that asks if setting up caching in other web frameworks is as easy as in Rails Ruby with Sinatra.

5 Responses to “Caching HTTP Responses with CherryPy”

  1. JoeJag Says:

    “This is in response to a post that asks if setting up caching in other web frameworks is as easy as in Rails.”

    Nice post for comparison, the other post isn’t using Rails though.

  2. christian Says:

    @JoeJag: Whoops! Thanks for pointing that out. I think whenever I see Ruby code written for the web I immediately think Rails.

  3. Pete Says:

    Very nice, but I prefer the Sinatra syntax. Is CherryPy RESTful?

  4. christian Says:

    Well, depends on what you mean by RESTful I guess. It supports nice looking URLs and supports dispatching based on HTTP methods. It doesn’t have out of the box dispatching based on Accept, but it is certainly something you can do. Basically CherryPy tries to give the developer access to everything that HTTP offers and let him/her make the decision on how to architect the application.

  5. Tarek Says:

    Cool,

    So caching is now a native CherryPy feature?

    By the way. I’ve created a CherryPy group in LinkedIn

    http://www.linkedin.com/groups?gid=1838298

Leave a Reply