我有一個名為 Org 的類,我試圖從多個函式(在類之外定義)訪問它的方法。我main()先打電話,然后是discover_buildings()。在main()沒有錯誤執行,但是,我得到AttributeError: 'Org' has no attribute 'headers' 的錯誤,我打電話后discover_buildings()。我做錯了什么?(我期待headers屬性在不同的方法之間共享)
class Org(object):
def __init__(self, client_id, client_secret, grant_type='client_credentials'):
self.grant_type = grant_type
self.client_id = client_id
self.client_secret = client_secret
self.url = CI_A_URL
def auth(self):
""" authenticate with bos """
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': self.grant_type
}
r = requests.post(self.url 'o/token/', data=params)
if r.status_code == 200:
self.access_token = r.json()['access_token']
self.headers = {
'Authorization': 'Bearer %s' %self.access_token,
'Content-Type': 'application/json',
}
else:
logging.error(r.content)
r.raise_for_status()
def get_buildings(self, perPage=1000):
params = {
'perPage': perPage
}
r = requests.get(self.url 'buildings/', params=params, headers=self.headers)
result = r.json().get('data')
if r.status_code == 200:
buildings_dict = {i['name']: i['id'] for i in result}
sheet_buildings['A1'].value = buildings_dict
else:
logging.error(r.content)
r.raise_for_status()
client_id = 'xxx'
client_secret = 'yyy'
gateway_id = 123
o = Org(client_id, client_secret)
def discover_buildings():
return o.get_buildings()
def main():
return o.auth()
在此先感謝您的幫助!
uj5u.com熱心網友回復:
嘗試使用屬性在需要時計算標題,然后將其快取。
def auth(self):
""" authenticate with bos """
# ??you might want to isolate `token` into a nested @property token
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': self.grant_type
}
# note assignment to `_headers`, not `headers`
r = requests.post(self.url 'o/token/', data=params)
if r.status_code == 200:
self._access_token = r.json()['access_token']
# ??
self._headers = { # ??
'Authorization': 'Bearer %s' %self._access_token,
'Content-Type': 'application/json',
}
else:
logging.error(r.content)
r.raise_for_status()
#cache after the first time.
_headers = None
@property
def headers(self):
""" call auth when needed
you might want to isolate `token`
into its own property, allowing different
headers to use the same token lookup
"""
if self._headers is None:
self.auth()
return self._headers
uj5u.com熱心網友回復:
問題是你定義“discover_buildings”的方式你首先用“o”定義它,而不是在認證之后初始化。
處理這個:
重寫發現以將 'o' 作為引數
或者
如果不驗證 'o',請先檢查 'o' 是否有 'headers' 并執行其余操作
def discover_buildings(): if not getattr(o, 'headers'): o.auth() return o.get_buildings()
uj5u.com熱心網友回復:
你沒有定義self.headers. 您需要在運行之前運行o.auth()(或定義self.headers)o.get_buildings()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/384571.html
下一篇:android類異步上傳參考
