提供用于缓存的实用程序和装饰程序
horae.cache的Python项目详细描述
简介
horae.cache包提供了用于缓存的简单装饰器。有装修工 可用于缓存词汇表(上下文或全局)以及缓存方法和 请求的函数输出。
用法
词汇
缓存词汇表有三种不同的方法:
- 全局缓存
- 全局缓存词汇表
- 上下文缓存
- 在给定上下文中缓存词汇表
- 上下文父缓存
- 将词汇缓存在给定上下文的已定义父级中
每种类型的缓存都有相应的失效函数来清除 给定的词汇。当使用动态词汇表 随时间变化,例如给定类型的内容对象词汇表:
import grok from zope.schema import vocabulary from some.module.interfaces import ISampleContent from horae.cache import vocabulary @vocabulary.cache_global def all_sample_contents(context): # find all content objects of type ISampleContent return vocab vocabulary.getVocabularyRegistry().register( 'allsamplecontents', all_sample_contents) @grok.subscribe(ISampleContent, grok.IObjectModifiedEvent) @grok.subscribe(ISampleContent, grok.IObjectMovedEvent) def invalidate_all_sample_contents_cache(obj, event): vocabulary.invalidate_global(all_sample_contents)
上下文缓存用于特定于上下文的词汇表,并以相同的方式使用 作为全局缓存:
@vocabulary.cache_contextual def sample_contents_in_context(context): # find all content objects of type ISampleContent # in the given context return vocab vocabulary.getVocabularyRegistry().register( 'samplecontentsincontext', sample_contents_in_context) @grok.subscribe(ISampleContent, grok.IObjectModifiedEvent) @grok.subscribe(ISampleContent, grok.IObjectMovedEvent) def invalidate_sample_contents_in_context_cache(obj, event): # iterate over all the parents of the object and call: vocabulary.invalidate_contextual(parent, sample_contents_in_context)
上下文父缓存的使用略有不同。它接受一个可选接口作为 查找要缓存词汇表的父级的参数。缓存会加速对象 层次结构,直到找到实现给定接口的父级。如果没有接口 假设词汇上下文的直接父级被视为缓存上下文。一个 示例用法如下:
from some.module.interfaces import ISampleContainer @vocabulary.cache_contextual_parent(ISampleContainer) def sample_contents_in_parent_of_context(context): # find all content objects of type ISampleContent in # the first found parent implementing ISampleContainer # of the given context return vocab vocabulary.getVocabularyRegistry().register( 'samplecontentsinparentofcontext', sample_contents_in_parent_of_context) @grok.subscribe(ISampleContent, grok.IObjectModifiedEvent) @grok.subscribe(ISampleContent, grok.IObjectMovedEvent) def invalidate_sample_contents_in_context_cache(obj, event): vocabulary.invalidate_contextual_parent( obj, ISampleContainer, sample_contents_in_parent_of_context)
请求
要缓存当前请求的函数输出,只需添加 horae.cache.request.cachedecorator:
from horae.cache import request @request.cache() def some_heavy_computation(arg1, arg2, kwarg1=True, kwarg2=True): # do the heavy computation return result_of_the_heavy_computation
horae.cache.request.cache接受两个可选参数args和kwargs 使用它可以定义哪些参数和/或关键字参数与 输出。如果在上面的示例中设置arg2和kwarg2,则输出将相同 不同的是,decorator可以像这样改进缓存:
@request.cache(args=(0,), kwargs=('kwarg1',)) def some_heavy_computation(arg1, arg2, kwarg1=True, kwarg2=True): # do the heavy computation return result_of_the_heavy_computation
更改日志
1.0a1(2012-01-16)
- 初始版本