def huancun_info(fun_name):
dict_info = {}
def fun(*args, **kwargs):
key = "-".join(args)
if key not in dict_info.keys():
info = fun_name(*args, **kwargs)
dict_info[key] = info
return info
else:
print("已缓存,直接返回数据")
return dict_info[key]
return fun
用法:使用@+huancun_info添加到需要缓存信息的函数名上方。
缺点:缓存的数据保存周期短,即从缓存装饰器开始执行时到整个程序运行结束。
优点:逻辑简单,容易。
基于普通文件的缓存
import re
import ast
def file_cache(fun_name):
def fun(*args, **kwargs):
filename = "-".join(args)
# 文件名中不能包含\/:*?"<>|,使用正则表达式将这些数据替换成空
pattern = re.compile("""(\\\|/|:|\*|\?|\"|<|>|\|)""")
filename = pattern.sub("", filename)
cache_path = f"{filename}.txt"
if not os.path.exists(cache_path):
result = fun_name(*args, **kwargs)
with open(cache_path, "w", encoding="utf-8") as f:
# 强制类型转换
result = str(result)
# 使用write写入文件操作,参数必须是字符串
f.write(result)
return result
else:
with open(cache_path, encoding="utf-8") as f:
result = f.read()
# 使用literal_eval函数将文件中读取的数据转换为原来的数据
result = ast.literal_eval(result)
return result
return fun