我試圖使用全局,但它給我Global NameError Not Defined。 它失敗的錯誤: UnboundLocalError:局部變量「full_url」如果你ENV不是staging
或prod
一個,這將失敗,因爲full_url
不會當打印執行組分配NameError:全局名稱'full_url'未定義
env = sys.argv[1]
class Account:
def __init__(self):
self.stag_url = 'http:url_1'
self.prod_url = 'http://url_2'
self.account_number = 'XXXXXXX'
self.api_url = "ZZZZZZ"
self.headers = { "Client": "ZZZZ", \
"content-type": "application/json", \
"Accept": "application/json;v=2" }
def request_data(self,env):
if env == "staging":
full_url = self.stag_url + self.account_number + self.api_url
if env == "prod":
full_url = self.prod_url + self.account_number + self.api_url
print("URL: " + full_url + '\n')
try:
req = requests.get(full_url,headers=self.headers)
return req.status_code, req.json()
except requests.exceptions.HTTPError as e:
print("Got an HTTPError: ", e.message)
acnt = Account()
if sys.argv[2] == "response_code":
status_code,response_json = acnt.request_data(env)
print("Response Code: " + str(status_code))
print('\n' + "Response JSON Body: " + '\n')
print(json.dumps(response_json, sort_keys=True, indent=4))
if sys.argv[2] == "response_json":
status_code,response_json = acnt.request_data(env)
print(json.dumps(response_json, sort_keys=True, indent=4))
很可能你的變量'env'沒有設置。你也應該修改你的縮進以便你的代碼可讀 – Cfreak
env已經被設置在類本身之上。 –
env的價值是什麼?第一個if(「staging」)和第二個(「prod」)匹配是否有可能在打印時沒有定義「full_url」? – Francesco