diskcache 简单试用
对于diskcache的特性以前简单介绍过
参考使用
diskcache 包含了好几种类型,比如默认的Cache,支持分片的FanoutCache,Django 兼容的,支持的操作包含了get,set,incr,decr
add,delete,pop,touch,evict,clear,reset,push,pull,stats,transact等
- 一个简单使用
from diskcache import Cache
cache = Cache("demo")
cache.set('name', 'demo')
print(cache.get('name'))
存储效果

- FanoutCache 模式使用
from diskcache import FanoutCache
cache = FanoutCache("app",shards=8)
cache.set("name","John")
print(cache.get("name"))
存储效果

说明
尽管diskcache基于了磁盘(内部基于sqlite 存储),但是我们可以扩展自己的序列化实现,比如官方的一个示例
import diskcache
import json
import zlib
from diskcache import FanoutCache
UNKNOWN = "UNKNOWN"
class JSONDisk(diskcache.Disk):
def __init__(self, directory, compress_level=1, **kwargs):
self.compress_level = compress_level
super().__init__(directory, **kwargs)
def put(self, key):
json_bytes = json.dumps(key).encode('utf-8')
data = zlib.compress(json_bytes, self.compress_level)
return super().put(data)
def get(self, key, raw):
data = super().get(key, raw)
return json.loads(zlib.decompress(data).decode('utf-8'))
def store(self, value, read, key=UNKNOWN):
if not read:
json_bytes = json.dumps(value).encode('utf-8')
value = zlib.compress(json_bytes, self.compress_level)
return super().store(value, read, key=key)
def fetch(self, mode, filename, value, read):
data = super().fetch(mode, filename, value, read)
if not read:
data = json.loads(zlib.decompress(data).decode('utf-8'))
return data
with FanoutCache("rong",disk=JSONDisk,shards=1) as cache:
cache.set("name","John")
print(cache.get("name"))
说明
diskcache 得功能还是不少的,值得在项目中使用下
浙公网安备 33010602011771号