在給我司寫一個環(huán)境資源大戶統(tǒng)計的腳本。遇到的一個問題是nova,cinder這種服務(wù)里面存的都是租戶的tenant id均澳。一串uuid,沒法對應(yīng)到人。
這倒是也好辦找前,keystone里面有個接口可以查出對應(yīng)tenant id的的tenant name糟袁。但是每次統(tǒng)計完都去查一遍keystone調(diào)起碼幾百次不是特傻(而且慢)。租戶id和名字這個映射屬于基本上都不會改的躺盛,應(yīng)該緩存起來项戴。
既然是腳本,那么就緩存到文件中好了槽惫。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
然后界斜,有了這個裝飾器之后仿耽,在需要緩存的函數(shù)前面加一下即可。如下:
@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
如果已經(jīng)緩存在文件中了各薇,那就直接讀文件项贺;如果沒讀到,就去查一下峭判,然后插到文件里敬扛。
超級方便有木有!朝抖!