9

我的ini文件中有以下内容:

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

这在我的__init__.py

from pyramid_beaker import set_cache_regions_from_settings
set_cache_regions_from_settings(settings)

但是,我不确定如何在我的视图/处理程序中执行实际缓存。有装修师傅吗?response我认为API中会有一些东西,但只有cache_control可用的东西——它指示用户缓存数据。不在服务器端缓存它。

有任何想法吗?

4

5 回答 5

12

我的错误是在可调用视图上调用装饰器函数@cache_region。我没有收到错误报告,但没有实际的缓存。因此,在我的 views.py 中,我尝试如下:

@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
    }

没有错误,也没有缓存。此外,您的 view-callable 将开始需要另一个参数!但这有效:

#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

然后在 view-callable 中:

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

与 @cache.cache 等的工作方式相同。

摘要:不要尝试缓存 view-callables

PS。我仍然有点怀疑可以缓存视图可调用对象:)

UPD.:正如 hlv 稍后解释的那样,当您缓存视图调用时,缓存实际上永远不会被命中,因为@cache_region使用可调用的请求参数作为缓存 id。每个请求的请求都是唯一的。

于 2011-11-27T07:03:45.183 回答
6

顺便说一句..调用 view_callable(request) 时它对您不起作用的原因是,函数参数被腌制到缓存键中,以便以后在缓存中查找。由于每个请求的“self”和“request”都会发生变化,因此返回值确实被缓存了,但永远无法再次查找。相反,您的缓存会因大量无用的键而变得臃肿。

我通过在视图可调用中定义一个新函数来缓存我的视图函数的一部分,例如

    def view_callable(self, context, request):

        @cache_region('long_term', 'some-unique-key-for-this-call_%s' % (request.params['some-specific-id']))
        def func_to_cache():
            # do something expensive with request.db for example
            return something
        return func_to_cache()

到目前为止,它似乎工作得很好..

干杯

于 2012-03-14T17:06:55.590 回答
4

您应该使用缓存区域:

from beaker.cache import cache_region

@cache_region('default_term')
def your_func():
    ...
于 2011-02-23T18:08:31.173 回答
2

对那些使用@cache_regionon 函数但没有缓存其结果的人的提示 - 确保函数的参数是标量的。

示例 A(不缓存):

@cache_region('hour')
def get_addresses(person):
    return Session.query(Address).filter(Address.person_id == person.id).all()

get_addresses(Session.query(Person).first())

示例 B(缓存):

@cache_region('hour')
def get_addresses(person):
    return Session.query(Address).filter(Address.person_id == person).all()

get_addresses(Session.query(Person).first().id)

原因是函数参数被用作缓存键 - 类似于get_addresses_123. 如果传递了一个对象,则无法生成此键。

于 2012-04-13T01:05:44.563 回答
1

同样的问题,您可以使用默认参数执行缓存

from beaker.cache import CacheManager

然后装饰器喜欢

@cache.cache('get_my_profile', expire=60)

喜欢http://beaker.groovie.org/caching.html,但我找不到如何使其与金字塔 .ini 配置一起使用的解决方案。

于 2011-02-20T01:51:02.750 回答