使用现代异步库的 2021 年答案
2016 年的答案很好,但我想我会用 httpx 而不是 aiohttp 提出另一个答案,因为 httpx 只是一个客户端并且支持不同的异步环境。我省略了 OP 的 for 循环,其 url 是由连接到字符串的数字构建的,因为我觉得这是一个更通用的答案。
import asyncio
import httpx
# you can have synchronous code here
async def getURL(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
# we could have some synchronous code here too
# to do CPU bound tasks on what we just fetched for instance
return response
# more synchronous code can go here
async def main():
response1, response2 = await asyncio.gather(getURL(url1),getURL(url2))
# do things with the responses
# you can also have synchronous code here
asyncio.run(main())
在等待的任务完成后,async with块中的任何await之后的代码将立即运行。这是一个解析您的响应的好地方,而无需等待您的所有请求完成。
asyncio.gather之后的代码将在所有任务完成后运行。这是一个执行需要来自所有请求的信息的操作的好地方,这些信息可能在gather调用的异步函数中进行了预处理。