我正在使用一个API,它根据成功/失败有不同的json响应。它们不是HTTP错误,而是json主体中的代码。你知道吗
有两个可能的错误代码(400和404),然后您就有了成功的API响应。你知道吗
以下三个示例包括一个成功的API调用:
j1 = {'status': '400','message': 'invalid'}
j2 = {'status': '404','message': 'wrong_info'}
j3 = {'info': 'your_info','other_info':'54321'}
假设我得到了回应,但我不知道是什么。(下面是一个成功的回答):
api_response = j3
{'info': 'your_info','other_info':'54321'}
根据它是什么,我将向数据帧添加数据,或者什么都不做:
for row in df:
# do API call and get api_response
# if the api response has an error code (first digit== 4), just skip it
if api_response['status'][:1]=='4':
pass
# if it has an 'info' key, do something
elif api_response['facebook']:
print('Found My Info')
检查status: 400 / 404
会导致错误。我以为else
会处理这个?你知道吗
KeyError Traceback (most recent call last)
<ipython-input-168-7a657630291c> in <module>
----> 1 if api_response['status'][:1]=='4':
2 pass
3 else:
4 if api_response['info']:
5 print('Found My Info')
KeyError: 'status'
我试过的
我添加了一个try except
,但感觉就像是把东西放在一起,忽略了问题。这是一个可以接受的或'Python'的方式来处理不同的反应像这样?另外,如果有400/404
状态,我是否正确地使用pass
跳过该行?你知道吗
try:
if api_response['status'][:1]=='4':
pass
except:
if api_response['info']:
print('Found My Info')
Found My Info
如果键不存在,可以使用^{} 返回默认值。你知道吗
您可以指定自己的默认值,否则为
None
尝试:
以及:
不,因为您试图访问一个不存在的密钥,所以首先需要测试它是否存在!你知道吗
相关问题 更多 >
编程相关推荐