安装
pip3 install cachetools
常见缓存分类
- class cachetools.Cache(maxsize, getsizeof=None)
- class cachetools.LRUCache(maxsize, getsizeof=None). Least Recently Used
- class cachetools.TTLCache(maxsize, ttl, timer=time.monotonic, getsizeof=None). Time To Live
- class cachetools.LFUCache(maxsize, getsizeof=None). Least Frequently Used
- class cachetools.RRCache(maxsize, choice=random.choice, getsizeof=None). Random Replacement
maxsize属性定义了在缓存开始淘汰旧条目之前的最大条目数
ttl属性定义了在缓存开始淘汰旧条目之前的最大时间,单位是秒
普通方式使用
from cachetools import Cache
#maxsize is the size of data the Cache can hold
cache_data = Cache(maxsize=50000)
data_item1 = "http://example1.com"
data_item2 = "http://example2.com"
data_item3 = "http://example3.com"
data_item4 = "http://example4.com"
data_item5 = "http://example5.com"
cache_data[hash(data_item1)] = data_item1
cache_data[hash(data_item2)] = data_item2
cache_data[hash(data_item3)] = data_item3
cache_data[hash(data_item4)] = data_item4
cache_data[hash(data_item5)] = data_item5
#Accessing data from cache
item = cache_data.get(hash(data_item4), None)
print("Getting from cache = ", item)
装饰器方式使用
使用装饰器方式的时候, key是返回值
返回值必须可以hash
- cached
from cachetools import cached
import time
# Without cached
def fib(n):
return n if n<2 else fib(n-1) + fib(n-2)
s = time.time()
print(old_fib(35))
print("Time Taken: ", time.time() - s)
# Now using cached
s = time.time()
# Use this decorator to enable caching
@cached(cache ={})
def fib(n):
return n if n<2 else fib(n-1) + fib(n-2)
print(fib(35))
print("Time Taken(cached): ", time.time() - s)
- LRUCache
def envkey(*args, env={}, **kwargs):
key = hashkey(*args, **kwargs)
key += tuple(sorted(env.items()))
return key
@cached(LRUCache(maxsize=128), key=envkey)
def foo(x, y, z, env={}):
pass
foo(1, 2, 3, env=dict(a='a', b='b'))