我试图缓存函数的返回值,以防它不是 None。
在下面的示例中,缓存 someFunction 的结果是有意义的,以防它设法从某个 URL 获取数据一小时。
如果无法获取数据,则缓存结果一小时(或更长时间)是没有意义的,但可能是 5 分钟(因此 some-domain.com 服务器有一些时间恢复)
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)
没有多大意义。
由于这段代码太长而无法发表评论,我将在此处发布它,希望它能帮助其他人:
#initialize cache
from zope.app.cache import ram
my_cache = ram.RAMCache()
my_cache.update(maxAge=3600, maxEntries=20)
_marker = object()
def _cachekey(lang):
return (lang, time.time() // (60 * 60))
def someFunction(self, lang='en'):
cached_result = my_cache.query(_cacheKey(lang), _marker)
if cached_result is _marker:
#not found, download, compute and add to cache
data = urllib2.urlopen('http://some-url.com/data.txt', timeout=10).read()
except socket.timeout:
data = None
except urllib2.URLError:
data = None
if data is not None:
#cache computed value for 1 hr
computed = expensive_compute(data)
my_cache.set(data, (lang, time.time() // (60 * 60) )
else:
# allow download server to recover 5 minutes instead of trying to download on every page load
computed = None
my_cache.set(None, (lang, time.time() // (60 * 5) )
return computed
return cached_result
在这种情况下,您不应该概括"返回为 None",因为装饰器缓存的结果只能依赖于输入值。
相反,您应该在函数中构建缓存机制,而不是依赖装饰器。
然后这就变成了一个通用的非 Plone 特定的 Python 问题,如何缓存值。
下面是如何使用 RAMCache 构建手动缓存的示例:
https://developer.plone.org/performance/ramcache.html#using-custom-ram-cache