繁体   English   中英

如何在金字塔中使用烧杯缓存?

[英]How do I use beaker caching in Pyramid?

我的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可用 - 它指示用户缓存数据。 不缓存服务器端。

有任何想法吗?

我的错误是在视图可调用上调用decorator函数@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

然后在视图中可调用:

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

它适用于@ cache.cache等。

简介: 不要尝试缓存view-callables

PS。 我仍然有点怀疑可以缓存视图callables :)

UPD。:正如hlv后来解释的那样,当你缓存一个view-callabe时,缓存实际上永远不会被命中,因为@cache_region使用callable的请求参数作为缓存id。 并且请求对于每个请求都是唯一的。

btw ..在调用view_callable(request)时它没有为你工作的原因是,函数参数被腌制到缓存键中以便以后在缓存中查找。 由于“self”和“request”会针对每个请求进行更改,因此返回值确实已缓存,但永远不会再次查找。 相反,你的缓存变得臃肿,有很多无用的密钥。

我通过在view-callable中定义一个新函数来缓存部分视图函数

    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()

到目前为止看起来工作得很好..

干杯

您应该使用缓存区域:

from beaker.cache import cache_region

@cache_region('default_term')
def your_func():
    ...

对于那些在函数上使用@cache_region但没有缓存结果的提示 - 确保函数的参数是标量。

示例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 如果传递了一个对象,则无法生成此密钥。

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

from beaker.cache import CacheManager

然后装饰者喜欢

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM