redis支持的python缓存
caches的Python项目详细描述
提供类似于标准接口的python缓存库 python数据结构,如dict和set,但由redis支持。
为First Opinion精心设计的缓存
如何使用
缓存只能使用Redis
缓存依赖于设置环境变量CACHES_DSN:
caches.interface.Redis://localhost/0
如果要使用多个redis服务器缓存内容,可以 实际设置多个环境变量:
export CACHES_DSN_1=caches.interface.Redis://somedomain.com/0#redis1 export CACHES_DSN_2=caches.interface.Redis://someotherdomain.com/0#redis2
设置环境变量后,只需导入 在代码中缓存:
importcaches
缓存将负责解析url并创建redis 连接,自动,因此导入后缓存将准备好 使用。
接口
所有缓存缓存类都有一个类似的接口,它们采用 传入构造函数*args并将其concat以创建密钥:
c=KeyCache('foo','bar','che')printc.key# foo.bar.che
如果要用值初始化缓存对象,请使用 data**kwarg:
c=KeyCache('foo',data="boom!")printc.key# fooprintc# "boom!"
每个缓存的基本缓存类都要进行扩展,以便您可以设置 一些参数:
- serialize–boolean–如果要对所有值进行pickle,则为true, 如果不这样做,则返回False(即,您正在缓存int或string或其他内容)
- prefix–string–这将在密钥参数前面 传入构造函数
- ttl–integer–生存时间,缓存 价值。默认设置为like 2小时,0表示直播
- 连接名称–字符串–如果有多个缓存 DSN然后您可以使用此设置所需连接的名称 (连接的名称是 dsn网址)
classMyIntCache(KeyCache):serialize=False# don't bother to serialize values since we're storing intsprefix="MyIntCache"# every key will have this prefix, change to invalidate all currently cached valuesttl=7200# store each int for 2 hours
缓存类
键缓存
这是传统的缓存对象,它将值设置为键:
c=KeyCache('foo')c.data=5# cache 5c+=10# increment 5 by 10, store 15 in the cachec.clear()printc# None
DictCache
这个缓存对象的行为或多或少类似于Python dictionary:
c=DictCache('foo')c['bar']='b'c['che']='c'forkey,valinc.iteritems():printkey,val# will print bar b and then che c
分类集缓存
这个缓存对象的行为或多或少类似于python set但是 一些更改:
- add()方法可以获取一个分数值
- pop()方法将弹出集合中的最低分数,然后 一个元组:(elem,score)
- rpop()方法允许您从集合中弹出最高分数。
- 迭代集合的结果是(elem,score)的元组,而不是 就像普通集合或SetCache中的元素一样
- chunk(limit,offset)和rchunk(limit,offset)方法将起作用 通过列表中向前或向后工作的部分
c=SortedSetCache('foo')c.add('bar',1)c.add('che',10)print'che'inc# Trueprintc.pop()# (bar, 1)
计数器缓存
这个缓存对象的行为或多或少类似于python collections.Counter:
c=CounterCache('foo')c['bar']=5c['bar']+=5printc['bar']# 10
装潢师
Caches公开一个decorator,使缓存的返回值为 功能简单这只适用于KeyCache派生缓存。
cacheddecorator可以接受缓存类和密钥 函数(类似于python内置的``sorted()` 函数<;http://docs.python.org/2/library/functions.html#sorted>;``键 参数),except caches key参数返回可以传递的列表 以*args的形式发送到缓存类的构造函数。
fromcachesimportKeyCache@KeyCache.cached(key="some_cache_key")deffoo(*args):returnreduce(lambdax,y:x+y,args)foo(1,2)# will compute the value and cache the return valuefoo(1,2)# return value from cachefoo(1,2,3)# uh-oh, wrong value, our key was too static
我们再试一次,这次是用动态键
@KeyCache.cached(key=lambda*args:args)deffoo(*args):returnreduce(lambdax,y:x+y,args)foo(1,2)# compute and cache, key func returned [1, 2]foo(1,2)# grabbed from cachefoo(1,2,3)# compute and cache because our key func returned [1, 2, 3]
自定义缓存类呢?
classCustomCache(KeyCache):pass@CustomCache.cached(key=lambda*args:args)deffoo(*args):returnreduce(lambdax,y:x+y,args)
安装
使用pypi中的pip:
pip install caches
或者使用pip从源代码:
pip install git+https://github.com/firstopinion/caches#egg=caches
许可证
麻省理工学院