gpt4 book ai didi

用于分页 API 资源的 Python 生成器

转载 作者:太空狗 更新时间:2023-10-29 18:29:00 26 4
gpt4 key购买 nike

所以我有这个 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")

在那里我可以遍历 smiths 中的每个“Smith”;如有必要,通过所有 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)

最佳答案

如果没有为您编写代码,您想利用 Python 的生成器,而不是将整个集合实现为列表。这样您就可以立即开始使用结果,并且仅在到达页面末尾时才执行分页请求。

for person in PeopleClient("http://ex..").get_people_by_last_name("smith"):
# Do something with the person

其次,您对实际请求的实现应该采用一个可以递增的页面参数,并且可以由包装器生成器调用。

def get_people_page(name, page):
# Perform the HTTP request, using page=page

生成器本身是这样的:

def get_all_people(name):
page = 0
has_more = 1
while has_more:
for person in get_people_page(name, page):
yield person
page += 1
has_more = # calculate has more by whether you have a next link
# or whether the results set is empty
# or whether you get an error

关于用于分页 API 资源的 Python 生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com