[英]asyncio - functions run sequentially instead of concurrently
I have a function that sends 2 different requests.我有一个发送 2 个不同请求的 function。 I need to call this function with different parameters 20 times.
我需要用不同的参数调用这个 function 20 次。
I would like to run the functions concurrently (different arguments) to spare some time between request and response.我想同时运行这些函数(不同的参数)以在请求和响应之间留出一些时间。
This is a very simplified function:这是一个非常简化的 function:
async def get_data(url):
return requests.get(url)
And this is how I call it:这就是我的称呼:
loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(get_data(url)) for url in websites.split('\n')]
group = asyncio.gather(*tasks)
results = loop.run_until_complete(group)
print(results)
loop.close()
The problem is that it runs sequentially instead of concurrently.问题是它按顺序运行而不是同时运行。
It's obvious that I'm missing something.很明显,我错过了一些东西。 Do you know what to do?
你知道该怎么做吗?
Don't wrap coroutine in asyncio.create_task
, use *
to unpack coroutins when passing to asyncio.gather
and call loop.run_until_complete
in the end不要将协程包装在
asyncio.create_task
中,在传递给asyncio.gather
时使用*
解压协程,最后调用loop.run_until_complete
loop = asyncio.get_event_loop()
tasks = [get_data(url) for url in websites.split('\n')]
group = asyncio.gather(*tasks)
results = loop.run_until_complete(group)
print(results)
loop.close()
Plus, it won't be concurrent because requests
isn't asynchronous, it's blocking the thread, you need to use alternative async HTTP clients like aiohttp
.另外,它不会并发,因为
requests
不是异步的,它会阻塞线程,您需要使用替代的异步 HTTP 客户端,如aiohttp
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.