Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use beaker caching in Pyramid?

I have the following in my ini file:

cache.regions = default_term, second, short_term, long_term
cache.type = memory
cache.second.expire = 1
cache.short_term.expire = 60
cache.default_term.expire = 300
cache.long_term.expire = 3600

And this in my __init__.py:

from pyramid_beaker import set_cache_regions_from_settings
set_cache_regions_from_settings(settings)

However, I'm not sure how to perform the actual caching in my views/handlers. Is there a decorator available? I figured there would be something in the response API but only cache_control is available - which instructs the user to cache the data. Not cache it server-side.

Any ideas?

like image 533
dave Avatar asked Feb 19 '11 10:02

dave


1 Answers

My mistake was to call decorator function @cache_region on a view-callable. I got no error reports but there were no actual caching. So, in my views.py I was trying like:

@cache_region('long_term')
def photos_view(request):
    #just an example of a costly call from Google Picasa
    gd_client = gdata.photos.service.PhotosService()
    photos = gd_client.GetFeed('...')
    return {
        'photos': photos.entry
    }

No errors and no caching. Also your view-callable will start to require another parameter! But this works:

#make a separate function and cache it
@cache_region('long_term')
def get_photos():
    gd_client = gdata.photos.service.PhotosService()
    photos = gd_client.GetFeed('...')
    return photos.entry

And then in view-callable just:

def photos_view(request):
    return {
        'photos': get_photos()
    }

The same way it works for @cache.cache etc.

Summary: do not try to cache view-callables.

PS. I still have a slight suspiction that view callables can be cached :)

UPD.: As hlv later explains, when you cache a view-callabe, the cache actually is never hit, because @cache_region uses callable's request param as the cache id. And request is unique for every request.

like image 183
yentsun Avatar answered Nov 03 '22 00:11

yentsun