Python 如果API没有';我什么也不退吗?
如果调用API时结果为空数组,如何停止脚本运行? 使用脚本,如果csv中有响应,我想写一个响应,但如果没有数据,它会出错,我想忽略响应并终止 这是我得到的json响应Python 如果API没有';我什么也不退吗?,python,api,Python,Api,如果调用API时结果为空数组,如何停止脚本运行? 使用脚本,如果csv中有响应,我想写一个响应,但如果没有数据,它会出错,我想忽略响应并终止 这是我得到的json响应 { “人”:[], “totalpeoplecount”:0, “状态”:“成功”, “信息”:[] } 这是我正在使用的代码 `def get_people(): url = testapi.com headers = {'Authorization': 'Token '+bd_login()} r = reques
{
“人”:[],
“totalpeoplecount”:0,
“状态”:“成功”,
“信息”:[]
}
这是我正在使用的代码
`def get_people():
url = testapi.com
headers = {'Authorization': 'Token '+bd_login()}
r = requests.get(url, headers=headers)
bdResponse = r.json()
people= bdResponse['people']
if bdResponse.get('people',[]):
exit(1)
return people`
如果你得到这个:
res = {
"people": [],
"totalpeoplecount": 0,
"status": "Success",
"messages": []
}
你可以:
if not res.get('people', []):
# Print something if you need
exit(1)
在没有看到代码的情况下,很难提出任何具体的建议,但显而易见的答案(现在出现在实际答案中)就是检查响应,如果响应为空,则使用if块跳过后续步骤。
if not results:sys.exit()
当我尝试使用此选项时,我发现发生了此异常:AttributeError'list'对象没有属性'get@user0015请用您正在使用的代码更新您的问题。@user0015 bdResponse应该是一个dict,而不是列表。您可以打印它吗?{'people':[],'totalpeoplecount':0,'status':'Success','messages':[]}@user0015AttributeError
没有意义。但是,从实际代码中,您可以将if
语句替换为:if not people:…