如何使用Python请求对带有偏移量参数的api调用进行分页
我需要重复进行api调用,因为每次调用1000条记录是有限制的。总共大约有20000条记录,我对它们进行了测试,保留了一个样本,然后需要请求下一个1000条。“偏移”参数可用如何使用Python请求对带有偏移量参数的api调用进行分页,python,python-2.7,api,python-requests,Python,Python 2.7,Api,Python Requests,我需要重复进行api调用,因为每次调用1000条记录是有限制的。总共大约有20000条记录,我对它们进行了测试,保留了一个样本,然后需要请求下一个1000条。“偏移”参数可用 p = getpass.getpass() url = ("https://example.api.com/api/1.0/devices/all/?offset={}&include_cols=asset_no,name,service_level,building&type=physical" r =
p = getpass.getpass()
url = ("https://example.api.com/api/1.0/devices/all/?offset={}&include_cols=asset_no,name,service_level,building&type=physical"
r = requests.get(url, auth=HTTPBasicAuth('admin', p))
data = json.loads(r.text)
payload = data["Devices"]
每次api调用时,偏移量值应增加1000(例如偏移量=1000、偏移量=2000、偏移量=3000等),直到检索到所有页面为止
如何创建使用此偏移量参数进行分页api调用的函数?我相信需要一个生成器,但我无法理解我找到的示例,以及我需要使用的偏移参数 由于您没有提供进一步的详细信息,也没有提到API供应商,因此我不得不将这一点非常笼统 分页可以使用一个简单的
while
循环来完成
基本工作流是,当您在中获取分页令牌时
你的回应,继续提出后续要求。在伪代码中
可能是这样的:
Page = GetPageOfItems();
//process the data from the page, or add it to a larger array, etc.
while( Page->cursor )
Page = GetPageOfItems(Page->cursor);
//process the data again
end
参考:
实现还取决于API的详细信息,例如,数据头是否包含当前的偏移量
和/或hasMore
键,例如
p = getpass.getpass()
offset=0
while True:
url = ("https://example.api.com/api/1.0/devices/all/?offset=" + offset + "&include_cols=asset_no,name,service_level,building&type=physical"
r = requests.get(url, auth=HTTPBasicAuth('admin', p))
data = json.loads(r.text)
# Process the payload or add it to a list
offset = data['offset'] # offset +1?
hasMore = data['has-more']
if not hasMore:
break