Ari*_*dem 3 python api python-2.7 python-requests
我需要重复进行 api 调用,因为每次调用有 1000 条记录的限制。我测试了大约 20,000 条记录,保留样本,然后需要请求下 1000 条。 offset 参数可用。
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"]
Run Code Online (Sandbox Code Playgroud)
每次 api 调用时,偏移值应增加 1000(例如,offset = 1000、offset = 2000、offset = 3000 等),直到检索到所有页面。
如何创建一个使用此偏移参数进行分页 api 调用的函数?我相信需要一个生成器,但我无法理解我找到的示例以及我需要使用的偏移参数。
我必须保持这一点非常笼统,因为您没有提供更多详细信息,也没有提到任何 API 供应商。
可以使用简单的循环来完成分页while。
基本工作流程是,当您在响应中获取分页令牌时,继续发出后续请求。在伪代码中可能如下所示:
Run Code Online (Sandbox Code Playgroud)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 endRef: https://medium.com/square-corner-blog/tips-and-tricks-for-api-pagination-5cacc6f017da
The implementation also depends on API details, e.g. does the data header contain the current offset and/or a hasMore key, e.g.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14943 次 |
| 最近记录: |