我正在使用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)
这是文档的链接。
您需要执行文档中建议的操作-
首次调用Search API会根据pageSize值返回有限数量的结果。调用响应的nextPageURL字段中返回的URL,将获得搜索结果的后续页面。
nextPageUrl-字符串-对该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
上面的代码应返回完整的订单列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句