gpt4 book ai didi

python - 如何使用 python 阅读 API 的下一页?

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:50 24 4
gpt4 key购买 nike

我需要有关如何执行循环的帮助,因此每次我发出 GET 请求时,它总是来自 API 的新页面。

我从获得第一个响应开始。它包括下一页的参数 next_key

{
"result": [
{
...,
...
}
],
"next_key": 123
}

下面是我目前的尝试

import requests
import json

url = "https://flespi.io/gw/channels/all/messages"
headers = {"Authorization": "FlespiToken 23ggh45"}

def getFirst():
data = {"limit_count":100, "limit_size":10000}
params = {"data":json.dumps(data, separators=(",", ":"))}

reqFirst = requests.get(url, params=params, headers=headers).json()
return reqFirst["next_key"] ## this returns "123"

def getDataNext():
data = {"limit_count":100, "limit_size":10000, "curr_key":getFirst()}
params = {"data":json.dumps(data, separators=(",", ":"))}

reqNext = requests.get(url, params=params, headers=headers)

jsonData = reqNext.json()

while True:
if "next_key" in jsonData:
data = {"limit_count":100, "limit_size":10000,"curr_key":jsonData["next_key"]}
params = {"data":json.dumps(data, separators=(",", ":"))}

req = requests.get(url, params=params, headers=headers).json() ## this should do GET request for the third page and so on...

print req["next_key"] # this returns "3321" which is the value for "next_key" in second page

else:
pass

getDataNext()

包含限制计数、限制大小和curr key的完整url如下https://flespi.io/gw/channels/all/messages?data=%7B%22curr_key%22%123%2C% 22limit_count%22%3A100%2C%22limit_size%22%3A10000%7D

如您所见,这仅返回第二页,即 jsonData["next_key"]。我想要做的是,对于每个 GET 请求,程序将读取 next_key 并将其放在下一个 GET 请求中。

我想在 curr_key 上使用增量,但 key 是随机的,而且我不知道有多少页。

我相信对此一定只有一个简单的解决方案,但显然我无法考虑。感谢您的帮助和建议。

最佳答案

试试这个

has_next_key = False
nextKey = ""

if "next_key" in jsonData:
has_next_key = True
nextKey = jsonData["next_key"]

while has_next_key:
data = {"limit_count":100, "limit_size":10000,"curr_key":nextKey}
params = {"data":json.dumps(data, separators=(",", ":"))}

req = requests.get(url, params=params, headers=headers).json() ## this should do GET request for the third page and so on...
if "next_key" in req:
nextKey = req["next_key"]
print nextKey # this returns "3321" which is the value for "next_key" in second page
else:
has_next_key = False
# no next_key, stop the loop

关于python - 如何使用 python 阅读 API 的下一页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293458/

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