Man*_*pta 4 python pagination python-requests
我正在使用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)
Run Code Online (Sandbox Code Playgroud)
这是文档的链接.
您需要执行文档建议的内容 -
第一次调用Search API会根据pageSize值返回有限数量的结果.调用响应的nextPageURL字段中返回的URL将获取搜索结果的后续页面.
nextPageUrl - String - 对此URL的GET调用将获取下一页结果.最后一页不存在
(强调我的)
您可以使用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
Run Code Online (Sandbox Code Playgroud)
上面的代码应该返回完整的订单列表.