易于使用函数和方法的缓存。
supercache被设计为与函数和方法一起使用的装饰器,只需额外一行代码即可提供几乎即时的重复执行。它充当缓存引擎的接口,缓存引擎可以是从内存缓存到使用 Redis 的任何内容(前提是已编码)。
请注意,使用装饰器会增加少量开销,因为它是为了性能的便利性和稳定性而设计的。缓存一个非常简单的函数可能会导致性能变差(每 40,000 次执行大约需要 1 秒)。
pip install supercache
from supercache import cache
# Basic cache
@ cache ()
def function ( x , y = None ):
return ( x , y )
# Set timeout
@ cache ( ttl = 60 )
def function ( x , y = None ):
return ( x , y )
# Ignore the y argument
@ cache ( ignore = [ 'y' ])
def function ( x , y = None ):
return ( x , y )
# Ignore anything after the first 2 arguments
@ cache ( keys = [ 0 , 1 ])
def function ( x , y = None , * args , ** kwargs ):
return ( x , y )
# Set up a custom cache engine
from supercache . engine import Memory
cache = Cache ( engine = Memory ( mode = Memory . FIFO , ttl = 600 , count = 100000 , size = 100000 ))
# Manually handle cache to reduce the decorator overhead
# This is in danger of collisions if the key is not unique
from supercache . exceptions import CacheError
def function ( x , y = None ):
key = 'function;{};{}' . format ( x , y )
try :
return cache . get ( key )
except CacheError :
value = ( x , y )
cache . put ( key , value )
return value
# Functions
@ cache ()
def function ():
pass
# Methods
class Class ( object ):
@ cache ()
def method ( self ):
pass
# Generators/iterators
@ cache ()
def generator ():
yield
# Lambdas
func = cache ()( lambda : None )
设置在生成缓存键时使用函数的哪些参数。默认情况下将使用所有可用参数。
这些格式可以是int
、 str
、 slice
(对于*args
有用)或regex
(对于**kwargs
有用)
设置生成缓存键时要忽略的参数。这将覆盖keys
中提供的任何设置。
这些也可以采用int
、 str
、 slice
或regex
的格式
覆盖引擎 ttl 设置以设置缓存失效前的秒数。
如果正在缓存的函数是生成器,则将其设置为True
会在首次调用时将输出转换为tuple
,而不是返回迭代器。
原因是生成器缓存有很大的开销,当调用一个简单的生成器数千次时,这可能会变得非常明显。
别名: cache[key]
读取缓存项,如果不存在则引发错误。
别名: cache[key] = value
设置一个新的缓存项。
别名: del cache[key]
删除键或函数的缓存。
cache.delete()
:删除所有缓存数据。cache.delete(key)
:删除特定key
的缓存数据。cache.delete(func)
:删除每次执行func
时的缓存数据。cache.delete(func, 1, b=2)
:删除func(1, b=2)
的缓存数据。返回某个键或函数读取缓存的次数。
cache.hits()
:缓存命中总数。cache.hits(key)
:特定key
的命中次数。cache.hits(func)
:每次执行func
时的缓存命中数。cache.hits(func, 1, b=2)
:专门针对func(1, b=2)
的缓存命中数。返回为键或函数生成缓存的次数。
cache.misses()
:缓存未命中总数。cache.misses(key)
:特定key
的未命中次数。cache.misses(func)
:每次执行func
时缓存未命中的次数。cache.misses(func, 1, b=2)
:专门针对func(1, b=2)
的缓存未命中次数。获取某个键或函数的缓存是否存在。
cache.exists()
:如果存在任何缓存。cache.exists(key)
:如果key
存在于缓存中。cache.exists(func)
:如果缓存中存在任何func
的执行。cache.exists(func, 1, b=2)
:如果func(1, b=2)
存在于缓存中。设置清除缓存的模式。选项包括 FIFO(先进先出)、FILO(先进后出)、LRU(最近最少使用)、MRU(最近使用)或 LFU(最不频繁使用)。
设置多少秒后缓存失效。
设置缓存结果的最大数量。
设置缓存的最大大小(以字节为单位)。这是一个软限制,首先分配内存,然后删除较旧的缓存,直到它回到限制以下。
即使最大大小设置为小于结果,最新执行也将始终被缓存。
classmethods
、 staticmethods
和properties
才能被缓存