使用 python 请求获取所有页面

Fetch all pages using python request

我正在使用 api 从网站获取订单。问题是它一次只能获取 20 个订单。我发现我需要使用分页迭代器但不知道如何使用它。如何一次获取所有订单。

我的代码:

def search_orders(self):
    headers = {'Authorization':'Bearer %s' % self.token,'Content-Type':'application/json',}
    url = "https://api.flipkart.net/sellers/orders/search"
    filter = {"filter": {"states": ["APPROVED","PACKED"],},}
    return requests.post(url, data=json.dumps(filter), headers=headers)

这里是 link 文档。

Documentation

您需要按照文档的建议进行操作 -

The first call to the Search API returns a finite number of results based on the pageSize value. Calling the URL returned in the nextPageURL field of the response gets the subsequent pages of the search result.

nextPageUrl - String - A GET call on this URL fetches the next page results. Not present for the last page

(强调我的)

您可以使用 response.json() 获取响应的 json。然后你可以检查标志 - hasMore - 看看是否有更多如果有,使用 requests.get() 获取下一页的响应,并继续这样做直到 hasMore 为假。例子-

def search_orders(self):
    headers = {'Authorization':'Bearer %s' % self.token,'Content-Type':'application/json',}
    url = "https://api.flipkart.net/sellers/orders/search"
    filter = {"filter": {"states": ["APPROVED","PACKED"],},}
    s = requests.Session()
    response = s.post(url, data=json.dumps(filter), headers=headers)
    orderList = []
    resp_json = response.json()
    orderList.append(resp_json["orderItems"])
    while resp_json.get('hasMore') == True:
        response = s.get('"https://api.flipkart.net/sellers{0}'.format(resp_json['nextPageUrl']))
        resp_json = response.json()
        orderList.append(resp_json["orderItems"])
    return orderList

以上代码应该return完整的订单列表。