标签: 协程

  • python使用协程循环并发执行http请求

    import asyncio
    import aiohttp
    
    async def do_request(val):
        timeout = aiohttp.ClientTimeout(total=86400)
        async with aiohttp.ClientSession(timeout=timeout) as session:
            async with session.post('http://127.0.0.1:5000'), json={"val": val}) as resp:
            result = await resp.json()
            return result
    
        async def main(count):
            tasks = [do_request(val) from val in range(count)]
            values = await asyncio.gather(*tasks)
            print(values)
    
    asyncio.run(main(10))
    

    参考:
    https://superfastpython.com/asyncio-for-loop/
    https://www.dongwm.com/post/understand-asyncio-1/
    https://www.dongwm.com/post/understand-asyncio-2/

    Views: 2