AsyncioSleep似乎无法满足某些状态码的限制
创始人
2024-09-21 07:00:41
0

在使用 asyncio 时,可以利用 asyncio.gather() 或者是 asyncio.wait() 进行一次执行多个协程。这样,如果一个协程出现了时间阻塞,那么其他协程依然可以同时执行,以达到更高的效率。

另外,在使用 asyncio.sleep() 时,需要注意传入的时间参数单位为秒而非毫秒。可以通过将时间除以 1000 的方式将毫秒转换为秒。此外,如果需要更精细的调度管理,可以使用 aiohttp-limiter 进行更灵活的控制。以下是一个使用 asyncio.gather() 解决 Asyncio Sleep 满足率限制的代码示例:

import asyncio
import aiohttp

async def fetch_page(session, url):
    async with session.get(url) as response:
        if response.status == 429:
            await asyncio.sleep(int(response.headers['Retry-After']))
        elif response.status == 200:
            await asyncio.sleep(0.5)
        else:
            print(f"Unhandled status code {response.status} for {url}")

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = []
        for i in range(10):
            task = fetch_page(session, f"http://example.com/page/{i}")
            tasks.append(task)
        await asyncio.gather(*tasks)

if __name__ == '__main__':
    asyncio.run(main())

在这个示例代码中,当 HTTP 响应状态为 429 时,我们使用了 asyncio.sleep(),它的参数获取自响应头的 Retry-After 值。当响应状态为 200 时,我们延迟了 0.5 秒 而不是使用了 asyncio.sleep()。

相关内容

热门资讯

解密透视!wepoker怎么挂... 解密透视!wepoker怎么挂飞机,wpk真吗,攻略教程(有挂头条)-哔哩哔哩1、wepoker怎么...
曝光透视!pokeplus脚本... 曝光透视!pokeplus脚本!一贯有辅助教程(有挂解密)-哔哩哔哩1、用户打开应用后不用登录就可以...
解迷透视!wepoker买脚本... 解迷透视!wepoker买脚本靠谱吗,wepoker透视底牌,方针教程(有挂工具)-哔哩哔哩1、用户...
分享透视!pokerrrr2辅... 分享透视!pokerrrr2辅助!总是真的有辅助技巧(有挂秘笈)-哔哩哔哩1、在pokerrrr2辅...
揭幕透视!we poker游戏... 揭幕透视!we poker游戏下,aapoker透视怎么用,窍要教程(有挂助手)-哔哩哔哩揭幕透视!...
专业透视!pokemmo辅助器... 专业透视!pokemmo辅助器!本来有辅助app(有挂秘笈)-哔哩哔哩1)pokemmo辅助器有没有...
揭露透视!拱趴大菠萝辅助神器,... 揭露透视!拱趴大菠萝辅助神器,aapoker破解侠是真的吗,大纲教程(有挂秘籍)-哔哩哔哩1、aap...
解密透视!来玩app破解!一贯... 解密透视!来玩app破解!一贯是真的有辅助教程(真的有挂)-哔哩哔哩1、游戏颠覆性的策略玩法,独创攻...
了解透视!拱趴大菠萝怎么开挂,... 了解透视!拱趴大菠萝怎么开挂,wepoker有辅助吗,教材教程(真的有挂)-哔哩哔哩1、用户打开应用...
推荐透视!德普之星怎么设置埋牌... 推荐透视!德普之星怎么设置埋牌,epoker免费透视脚本,举措教程(有挂功能)-哔哩哔哩1、德普之星...