在給我司寫一個環(huán)境資源大戶統(tǒng)計的腳本。遇到的一個問題是nova,cinder這種服務里面存的都是租戶的tenant id。一串uuid,沒法對應到人。
這倒是也好辦,keystone里面有個接口可以查出對應tenant id的的tenant name。但是每次統(tǒng)計完都去查一遍keystone調起碼幾百次不是特傻(而且慢)。租戶id和名字這個映射屬于基本上都不會改的,應該緩存起來。
既然是腳本,那么就緩存到文件中好了。google一下,有個現(xiàn)成的輪子。
# cache, use json to store cache
def persist_to_file(file_name):
def decorator(original_func):
try:
cache = json.load(open(file_name, 'r'))
except (IOError, ValueError):
cache = {}
def new_func(param):
if param not in cache:
cache[param] = original_func(param)
json.dump(cache, open(file_name, 'w'), indent=4)
return cache[param]
return new_func
return decorator
然后,有了這個裝飾器之后,在需要緩存的函數前面加一下即可。如下:
@persist_to_file('cache.dat')
def tenantid_to_tenant_name(tenantid):
headers = {'X-Auth-Token': TOKEN}
r = requests.get(
"{}:35357/v2.0/tenants/{}".format(HA, tenantid),
headers=headers)
result_json = json.loads(r.text)
name = result_json['tenant']['name']
return name
如果已經緩存在文件中了,那就直接讀文件;如果沒讀到,就去查一下,然后插到文件里。
超級方便有木有??!