【问题标题】:Asyncio - how to limit requests per 1 second?Asyncio - 如何限制每 1 秒的请求?
【发布时间】:2021-11-18 07:52:08
【问题描述】:

我是 asyncio 的新手,试图对 API 进行异步调用,但是当我发送超过 1 个请求/秒时,API 以 429 状态代码响应 - 请求太多...根据 API 文档,我应该只做 1 个请求/秒。

无法弄清楚如何每秒只有 1 个请求

#Call to API
async def ps_request_marshal(converted_urls, device_input):
    global device_settings, data, tasks
    data = []
    device_settings = device_input
    tasks = []
    url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={}' '&key=+key &strategy=' +device_input

    async with aiohttp.ClientSession() as session:
        for page in converted_urls:
            tasks.append(asyncio.create_task(session.get(url.format(page), ssl=False)))
        responses = await asyncio.gather(*tasks)
        for response in responses:
            data.append(await response.json())
        print(responses)

非常感谢您的帮助!

【问题讨论】:

    标签: python api asynchronous python-asyncio aiohttp


    【解决方案1】:

    已解决,刚刚在任务创建循环中添加了“await asyncio.sleep(delay_per request)”。

    async def ps_request_marshal(converted_urls, device_input):
        global device_settings, data, tasks
        data = []
        device_settings = device_input
        tasks = []
        url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={}' '&key=key=' +device_input
        delay_per_request = 1
        async with aiohttp.ClientSession() as session:
            for page in converted_urls:
                tasks.append(asyncio.create_task(session.get(url.format(page), ssl=False)))
                await asyncio.sleep(delay_per_request)
            responses = await asyncio.gather(*tasks)
            print(responses)
            for response in responses:
                data.append(await response.json())
            print(responses)
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      相关资源
      最近更新 更多