使用python循环分页API

2024-10-02 14:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从下面的RESTAPI检索所有设备,但是API JSON响应被限制为10k行。下面的代码只返回40行,不知道为什么。我如何发送多个请求以检索所有设备以超过10k行限制

https://developer.carbonblack.com/reference/carbon-black-cloud/platform/latest/devices-api/

n是从另一个python函数检索的json响应中的“num_found”,它是注册的设备总数

def getdevices(n):
    param = {
        "criteria": {"status": ["ACTIVE"], "target_priority": ["LOW", "MEDIUM", "HIGH", "MISSION_CRITICAL"]}
    }

    all_endpoints = []
    # loop through all  and return JSON object
    for start in range(0, n, 10001):
        r = requests.post(hostname+f'/appservices/v6/orgs/abcdefg/devices/_search?start={start}&rows=10000', data=json.dumps(param), headers=headers)
        if r.status_code != 200:
            logging.error('status code ' + str(r.status_code))
            logging.error('unable to get devices! ' + r.text)
            sys.exit(1)
        else:
            response = json.loads(r.text)
            r = response['results']
            for d in r:
                all_endpoints.append({k: d[k] for k in ("id", "registered_time", "last_contact_time",
                                                          "last_external_ip_address", "last_internal_ip_address",
                                                          "last_location", "login_user_name", "name")})
        return all_endpoints

另一个例子是下面网页上的CURL命令,对于上面的代码,我如何使用python的类似方法来检索所有设备? https://community.carbonblack.com/t5/Knowledge-Base/Carbon-Black-Cloud-How-To-Use-API-Pagination/ta-p/40205

谢谢


Tags: 代码inhttpsapijsonforstatuscode