如何在进行异步API调用时限制Grequests?

2024-03-29 14:43:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用grequests库传递大约250000个url来从api获取数据。你知道吗

API限制为每秒100次调用。你知道吗

如何限制grequests每秒只传递100个url?我将size参数从5增加到100。不确定这是做什么,但仍然运行到错误'最大重试次数超过'。你知道吗

以下是我目前的代码:

import grequests

lst = ['url.com','url2.com']

class Test:
    def __init__(self):
        self.urls = lst

    def exception(self, request, exception):
        print ("Problem: {}: {}".format(request.url, exception))

    def async(self):
        return grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=100)

    def collate_responses(self, results):
        return [x.text for x in results]

test = Test()
#here we collect the results returned by the async function
results = test.async()

response_text = test.collate_responses(results)

Tags: testselfcomurlsizeasyncreturnrequest
1条回答
网友
1楼 · 发布于 2024-03-29 14:43:40

Grequests似乎发出100个请求,然后在没有任何等待的情况下再发出100个请求,以此类推。这些请求之间没有定义时间。 下面是一个与解决方案类似的问题: Limiting/throttling the rate of HTTP requests in GRequests

相关问题 更多 >