使用 Python 中的请求库制作请求数组

Making Array Of Requests Using Requests Library In Python

在从另一个 API 请求中获取数组后,我正在使用请求库来映射请求数组。我正在为请求使用循环,但我确信有更好的方法来执行此操作,因为此 API 请求可以包含 500 多个项目,因此完成此循环有时需要 20 多分钟。

我尝试使用 grequests 库,但不断收到递归投诉。如果可能的话,我很想使用 async/map 方法,但经过研究显然不再支持异步库。

self.set_header("Access-Control-Allow-Origin", "*")
response = requests.get("https://hacker-news.firebaseio.com/v0/paststories.json?print=pretty")
data = response.json()
story_list = []

for story in data:
    temp_string = "https://hacker-news.firebaseio.com/v0/item/{}.json?print=pretty".format(story)
    story_data = requests.get(temp_string)
    story_list.append(story_data.json())

应该有比当前方法更好的方法来执行此循环,因为 20 分钟以上的时间来获取数据是不可接受的。原始数组中的 API 响应可以 return 500+ 的数组,因此该方法应该是可扩展的。

requests 是同步的,因此您的脚本等待响应以发出新请求。 所以也许您应该研究一下 aiohttp 和异步请求。

这可能是一个例子:

嗯,你只需要提高你的io-bond代码速度,解决方法有提示,请参考Whosebug中的相关答案:How could I use requests in asyncio?

由于 asyncio 太基础了,有很多基于它构建的包,试试这个包:aiohttp-requests

希望这些信息对您有所帮助。