易於使用函數和方法的快取。
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
才能被緩存