Pylons tip #3: Easy caching with Beaker

November 18, 2008 at 06:30 PM | categories: Technical, Python | View Comments |

Pylons ships with Beaker, which provides some very useful caching functionality. While there are a bunch of ways to use it, I like the handy decorator, @beaker_cache. To use it, simply wrap up your response-generating function call like so:

from pylons.decorators.cache import beaker_cache
class MyController(BaseController):
# ...
    @beaker_cache(expire=600, type='memory')
    def rss(self):
        ''' generate RSS feed '''
        feed = Atom1Feed(...)
        # do some stuff, like add items to the feed
        response.content_type = 'application/atom+xml'
        return feed.writeString('utf-8')
This will automatically handle caching the output of your rss() method in memory, with a lifetime of 600 seconds (10 minutes). Of course, there are a number of other parameters supported by @beaker_cache. Read the docs here.

Niall O'Higgins is an author and software developer. He wrote the O'Reilly book MongoDB and Python. He is the co-founder of BeyondFog, Inc which makes Strider Brilliant Continuous Deployment. Strider is a hosted Continuous Integration & Deployment service for Node.JS and Python.

blog comments powered by Disqus