当处理Python字典的键错误时,除了块之外,是不工作的,但是块是工作的。
下面是我的代码
def catch_empty_key(a):
try:
return 'aaaa'
except :
return 'bbbb'
def zohoapicall(accesstoken):
accesstoken = ""
if accesstoken == "":
parameters = {
"refresh_token":"1000.06f10f49d6f00478887e3820634b928f.c045ff2a9dcb9c99057ec42645bf1e44",
"client_id":"1000.UKZQIWVQ2A2THKSZ2126Y7E7CAA8CW",
"client_secret":"91d25fbaeea0e81190a681708cd554a1030a9c4547",
"redirect_uri":"https://www.google.com",
"grant_type":"refresh_token",
}
response = requests.post("https://accounts.zoho.com/oauth/v2/token?", params=parameters)
if response.status_code == 200:
data = response.json()
accesstoken = data['access_token']
headers = {
'Content-Type':'application/json',
'Authorization':'Zoho-oauthtoken ' + str(accesstoken)
}
response = requests.get("https://books.zoho.com/api/v3/invoices", headers=headers)
if response.status_code == 200:
data1 = response.json()
data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']]
return HttpResponse(data_2, accesstoken)在第二行的最后一行中,data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']] except块的catch_empty_key函数不能工作,它正在抛出一个错误。
另一方面,如果我将第二行替换为key of invoice,那么try块正在工作,并返回aaa作为输出。例如
data_2=[catch_empty_key(invoice['is_a_key']) for invoice in data1['invoices']] 我想知道为什么会出现这个错误,我们如何解决它?
发布于 2022-10-17 20:33:02
你误解了“尝试”的概念--除了。代码段需要在try块内,以便捕获在代码段中引发的任何异常。在给定的代码中,您可以将其用于requests.get(),如下所示:
headers = {
'Content-Type':'application/json',
'Authorization':'Zoho-oauthtoken ' + str(accesstoken)
}
try:
response = requests.get("https://books.zoho.com/api/v3/invoices", headers=headers)
except Exception as e:
print(e)
if response.status_code == 200:
data1 = response.json()
data_2=[catch_empty_key(invoice['not_a_key']) for invoice in data1['invoices']]
return HttpResponse(data_2, accesstoken)发布于 2022-10-17 20:44:11
在解析要传递的参数时会产生错误,因此在计算函数之前会失败;修改函数参数以便在函数中检查键就可以了,例如:
def catch_empty_key(dict_to_check, key):
try:
dict_to_check[key] # error will occur if key does not exist
return 'aaaa'
except:
return 'bbbb'或者,您可以使用in检查密钥是否存在。
test = {'my':'dictionary'}
print('j' in test)产出:
False所以你只需要:
def catch_empty_key(dict_to_check, key):
if key in dict_to_check:
return 'aaaa'
else:
return 'bbbb'https://stackoverflow.com/questions/74102809
复制相似问题