plone.memoize缓存取决于函数的返回值 [英] plone.memoize cache depending on function's return value

查看:110
本文介绍了plone.memoize缓存取决于函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仅在不返回None的情况下才尝试缓存函数的返回值.

i'm trying to cache the return value of a function only in case it's not None.

在以下示例中,如果它设法从some-url获取数据一个小时,则缓存someFunction的结果是有意义的.

in the following example, it makes sense to cache the result of someFunction in case it managed to obtain data from some-url for an hour.

如果无法获取数据,则将结果缓存一个小时(或更长时间),但可能要缓存5分钟(因此some-domain.com的服务器有一些时间可以恢复)是没有意义的

if the data could not be obtained, it does not make sense to cache the result for an hour (or more), but probably for 5 minutes (so the server for some-domain.com has some time to recover)

def _cachekey(method, self, lang):
    return (lang, time.time() // (60 * 60))

@ram.cache(_cachekey)
def someFunction(self, lang='en'):
    data = urllib2.urlopen('http://some-url.com/data.txt', timeout=10).read()

    except socket.timeout:
        data = None
    except urllib2.URLError:
        data = None

    return expensive_compute(data)

在_cachekey中调用method(self, lang)毫无意义.

calling method(self, lang) in _cachekey would not make a lot of sense.

推荐答案

在这种情况下,您不应该将"return as None"一概而论,因为装饰器缓存的结果只能取决于输入值.

In this case, you should not generalize "return as None", as decorator cached results can depend only on input values.

相反,您应该在函数内部构建缓存机制,而不要依赖装饰器.

Instead, you should build the caching mechanism inside your function and not rely on a decorator.

然后,这成为如何缓存值的非克隆特定的通用Python问题.

Then this becomes a generic non-Plone specific Python problem how to cache values.

这是一个如何使用RAMCache建立手动缓存的示例:

Here is an example how to build your manual caching using RAMCache:

https://developer.plone.org/performance/ramcache.html#using-custom-ram-cache

这篇关于plone.memoize缓存取决于函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆