简体   繁体   English

使用python请求获取所有页面

[英]Fetch all pages using python request

I am using an api to fetch orders from a website.我正在使用 api 从网站获取订单。 The problem is at one time it only fetch only 20 orders.问题是它一次只能获取 20 个订单。 I figured out i need to use a pagination iterator but dont know to use it.我发现我需要使用分页迭代器,但不知道如何使用它。 How to fetch all the orders all at once.如何一次获取所有订单。

My code:我的代码:

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)

Here is a link to documentation.这是文档的链接。

Documentation 文档

You need to do what the documentation suggests - 您需要执行文档建议的内容 -

The first call to the Search API returns a finite number of results based on the pageSize value. 第一次调用Search API会根据pageSize值返回有限数量的结果。 Calling the URL returned in the nextPageURL field of the response gets the subsequent pages of the search result. 调用响应的nextPageURL字段中返回的URL将获取搜索结果的后续页面。

nextPageUrl - String - A GET call on this URL fetches the next page results. nextPageUrl - String - 对此URL的GET调用将获取下一页结果。 Not present for the last page 最后一页不存在

(Emphasis mine) (强调我的)

You can use response.json() to get the json of the response. 您可以使用response.json()来获取响应的json。 Then you can check the flag - hasMore - to see if there are more if so, use requests.get() to get the response for next page, and keep doing this till hasMore is false. 然后你可以检查标志 - hasMore - 看看是否还有更多,如果是,请使用requests.get()来获取下一页的响应,并继续这样做直到hasMore为false。 Example - 示例 -

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

The above code should return the complete list of orders. 上面的代码应该返回完整的订单列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM