Pylons tip #3: Easy caching with Beaker

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:

1
2
3
4
5
6
7
8
9
10
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.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">