[英]Python: cannot access class attribute from different modules/functions
我有一個名為 Org 的 class,我試圖從多個函數(在類外部定義)訪問它的方法。 我首先調用main()
,然后是discover_buildings()
。 main()
執行沒有錯誤,但是,我在調用discover_buildings()
后得到AttributeError: 'Org' has no attribute 'headers'
錯誤。 我做錯了什么? (我期待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()
在此先感謝您的幫助!
問題是您定義“discover_buildings”的方式,您首先用“o”定義它,而不是在身份驗證之后初始化。
處理這個:
重寫discover以'o'作為參數
或者
如果沒有驗證“o”,請先檢查“o”是否有“標題”並執行 rest
def discover_buildings(): if not getattr(o, 'headers'): o.auth() return o.get_buildings()
嘗試在需要時使用屬性來計算標頭,然后將其緩存。
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
您沒有定義self.headers
。 您需要在運行 o.get_buildings() 之前運行o.auth()
(或定義self.headers
o.get_buildings()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.