python实现API调用缓存
- 1.代码
- 2.输出
- 3.保存的json数据
想把python某些函数的参数及返回值记录下来,如果之前已计算过,则直接返回缓存中的数据
1.代码
import json
def get_variable_name(var):
'''变量转变量名'''
local_vars=globals()
return [name for name, value in local_vars.items() if value is var][0]
def quick_exec(func,params):
'''通过参数生成UUID,如果缓存中存在则直接获取,否则执行实际的函数,之后保存结果'''
cache_path="cache_data.json"
records={}
uuid="_".join([str(x) for x in params])
try:
with open(cache_path,"r") as f:
records=json.load(f)
except:
pass
if uuid in records:
ret=records[uuid]["result"]
else:
ret=func(params)
records[uuid]={"result":ret,"params":{}}
for var in params:
records[uuid]["params"][get_variable_name(var)]=var
with open(cache_path,"w") as f:
json.dump(records,f,indent=4)
return ret
def sdk_api(params):
'''实际的调用'''
print("sdk_api call in:",params)
return sum(params)
def l0():
globals()['a']=1
globals()['b']=2
globals()['c']=3
globals()['d']=4
globals()['e']=5
params=(globals()['a'],globals()['b'],globals()['c'],globals()['d'],globals()['e'])
ret=quick_exec(lambda x:sdk_api(x),params)
print(ret)
ret=quick_exec(lambda x:sdk_api(x),params)
print(ret)
globals()['b']=3
params=(a,b,c,d,e)
ret=quick_exec(lambda x:sdk_api(x),params)
print(ret)
ret=quick_exec(lambda x:sdk_api(x),params)
print(ret)
def l1():
l0()
def main():
l1()
main()
2.输出
# 第一次运行
sdk_api call in: (1, 2, 3, 4, 5)
15
15
sdk_api call in: (1, 3, 3, 4, 5)
16
16
# 第二次运行
15
15
16
16
3.保存的json数据
{
"1_2_3_4_5": {
"result": 15,
"params": {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
},
"1_3_3_4_5": {
"result": 16,
"params": {
"a": 1,
"b": 3,
"d": 4,
"e": 5
}
}
}