所以我有一个带有集合的 RESTful API people
,可以这样调用:
http://example.com/people?lastname=smith
它返回如下 JSON 响应:
{
"page": 0,
"next": 1,
"total": 5000000,
"people": [
{
"firstname": "John",
"lastname": "Smith",
"age": 32
},
{
"firstname": "Adam",
"lastname": "Smith",
"age": 84
},
...
}
我想编写一个 Python 生成器,它将从响应中产生每个人,当它到达最后一个人时,如果有下一页,它将发出对下一页的请求,http://example.com/people?lastname=smith&page=1
并继续无缝地迭代结果。生成的类调用将非常简单:
client = PeopleClient("http://example.com/people")
smiths = client.get_people_by_last_name("smith")
然后我可以在其中迭代每个“Smith” smiths
;如有必要,通过全部 500 万。
关于如何实现这一点或是否有可能的任何想法?
更新
使用@ali-afshar 的答案作为指导,这个实现应该适用于假设的 REST API:
import requests
class PeopleClient:
def __init__(self, url):
self._url = url
def _get_people(self, **kwargs):
return requests.get(self._url, params=kwargs)
def get_people_by_last_name(self, lastname):
current_page = 0
while current_page >= 0:
result = self._get_people(lastname=lastname, page=current_page)
for person in result.get("people", []):
yield person
current_page = result.get("next", -1)