Python 实现cache功能
2022-04-12 本文已影响0人
Yohann丶blog
WechatIMG911.jpeg
- 创建 cache.py,代码如下
# -*- coding: utf-8 -*-
# !python3
import hashlib
import os
import pickle
cache_root_dir = 'cache'
if not os.path.exists(cache_root_dir):
os.makedirs(cache_root_dir)
def md5(s):
m = hashlib.md5()
m.update(s)
return m.hexdigest()
def cache_key(f, *args, **kwargs):
s = '%s-%s-%s' % (f.__name__, str(args), str(kwargs))
return os.path.join(cache_root_dir, '%s.dump' % md5(s.encode("utf-8")))
def cache(f):
def wrap(*args, **kwargs):
fn = cache_key(f, *args, **kwargs)
if os.path.exists(fn):
print('loading cache')
with open(fn, 'rb') as fr:
return pickle.load(fr)
obj = f(*args, **kwargs)
with open(fn, 'wb') as fw:
pickle.dump(obj, fw)
return obj
return wrap
@cache
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(6, 4))
print(add(6, 4))
print(add(7, 4))
print(add(7, 8))
- 执行
$ python3 cache.py
10
loading cache
10
11
15