实现cache装饰器
from functools import wraps
import time
import inspect
import datetime
def func_cache(fn):
local_cache = {}
@wraps(fn)
def wrapper(*args,**kwargs):
print("传入参数: ",args,kwargs)
key_dict = {}
sig = inspect.signature(fn)
params = sig.parameters
print("params: ",params)
patam_list = list(params.keys())
for i,v in enumerate(args):
k = patam_list[i]
key_dict[k] = v
key_dict.update(kwargs)
for k in params.keys():
if k not in key_dict.keys():
print("default: ",params[k].default)
key_dict[k] = params[k].default
key = tuple(sorted(key_dict.items()))
if key not in local_cache.keys():
ret = fn(*args,**kwargs)
local_cache[key] = ret
return local_cache[key]
return wrapper
def logger(fn):
@wraps(fn)
def wrapper(*args,**kwargs):
start = datetime.datetime.now()
ret = fn(*args,**kwargs)
delta = (datetime.datetime.now()-start).total_seconds()
print("spand time: {}秒".format(delta))
print("=="*20)
return ret
return wrapper
@logger
@func_cache
def add(x,y=5):
time.sleep(3)
ret = x+y
print("result: ",ret)
return ret
add(4,5)
add(4)
add(4,y=5)
add(x=4,y=5)
add(y=5,x=4)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f26070bd0ac69e8123d0238a43aab0f1.png)
实现过期清除
from functools import wraps
import time
import inspect
import datetime
def func_cache(duration):
def _cache(fn):
local_cache = {}
@wraps(fn)
def wrapper(*args,**kwargs):
print("传入参数: ",args,kwargs)
expire_keys = []
for k,(_,ts) in local_cache.items():
if datetime.datetime.now().timestamp()-ts > duration:
expire_keys.append(k)
for k in expire_keys:
local_cache.pop(k)
key_dict = {}
sig = inspect.signature(fn)
params = sig.parameters
print("params: ",params)
patam_list = list(params.keys())
for i,v in enumerate(args):
k = patam_list[i]
key_dict[k] = v
key_dict.update(kwargs)
for k in params.keys():
if k not in key_dict.keys():
print("default: ",params[k].default)
key_dict[k] = params[k].default
key = tuple(sorted(key_dict.items()))
if key not in local_cache.keys():
ret = fn(*args,**kwargs)
local_cache[key] = (ret,datetime.datetime.now().timestamp())
return local_cache[key]
return wrapper
return _cache
def logger(fn):
@wraps(fn)
def wrapper(*args,**kwargs):
start = datetime.datetime.now()
ret = fn(*args,**kwargs)
delta = (datetime.datetime.now()-start).total_seconds()
print("spand time: {}秒".format(delta))
print("=="*20)
return ret
return wrapper
@logger
@func_cache(5)
def add(x,y=5):
time.sleep(3)
ret = x+y
print("result: ",ret)
return ret
add(4,5)
add(4)
add(4,y=5)
add(x=4,y=5)
add(y=5,x=4)
print('---'*20)
time.sleep(6)
add(4,5)
add(4)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7304caa99056e3778d0ac9a86ba19d78.png)