Python requests调用OData接口@odata.nextLink缺失报KeyError如何解决
解决方案
错误原因
首次获取@odata.nextLink字段时直接使用字典键索引q_1['@odata.nextLink'],当返回数据量不足250行时接口不会返回该字段,直接索引就会抛出KeyError。你后续循环中使用的dict.get()方法本身已经兼容字段不存在的场景,只需要把首次取值的逻辑也调整为相同写法即可。
注:原代码还存在变量名笔误,上方定义的请求地址变量为
url1,下方发起请求时用了url_1,调整代码时注意统一变量名。
调整后代码
proxies = {'https': 'proxy.***.***.com:8080'} headers = {"grant_type": "password", "username": "****", "password": "****", "persistent": "true", "device": '{"DeviceUniqueId":"b680c452","Name":"Chrome","DeviceVersion":"36","PlatformType":"Browser"}'} url1 = 'https://****-***.com/odata/Results' params_1 = ( ('$filter', mod_date), ('$count', 'true'), ('$select', 'Status'), ('$expand', 'Result($select=ResultId),Specification($select=Name), SpecificationItem($select=Name,MinimumValue, MaximumValue)\n\n'),) response_1 = requests.get(url1, headers=headers, proxies=proxies, params=params_1) q_1 = response_1.json() # 仅修改这一行,改用get方法取值,不存在时返回None next_link_1 = q_1.get('@odata.nextLink', None) q_1 = [tuple(q_1.values())] while next_link_1: new_response_1 = requests.get(next_link_1, headers=headers, proxies=proxies) new_data_1 = new_response_1.json() q_1.append(tuple(new_data_1.values())) next_link_1 = new_data_1.get('@odata.nextLink', None)
逻辑说明
dict.get(键, 默认值)方法会在键存在时返回对应值,键不存在时返回你指定的默认值,不会抛出KeyError- 若首次请求没有分页链接,
next_link_1会被赋值为None,后续while循环不会执行,直接保留首次请求拿到的所有数据 - 原有分页逻辑完全保留,数据量超过250行时依然可以正常拉取全量分页数据
内容的提问来源于stack exchange,提问作者Premier12
相关产品推荐
相关产品推荐

