为什么不应该等待

时间:2021-05-28 09:58:07

标签: python python-3.x

下面是我的代码。我不明白一件事。由于我删除了以下两行的 await 关键字:

response1 = await session.post("https://a")  
response2 = await session.post("https://b")  

我希望立即看到输出:

Requesting response1...
Requesting response2...

尽管如此,我只看到程序运行时:

Requesting response1..

虽然它处理 request1 但对我来说应该打印第二个文本。为什么会这样?

我的代码:

import asyncio
from pip._vendor import requests

async def getrequest():
    session = requests.Session()

    
    try:
        print("Requesting response1...")
        response1 = session.post("https://a")  # SEE > i am not awaiting here
        print("Requesting response2...")
        response2 = session.post("https://b")  # SEE > i am not awaiting here

        await response1;
        await response2;

        print("Getting response ...")
        print(f"Code status is: {response1.status_code}")
        print(response1.json())
        print("Done")
    except Exception as err:
        print(f"An error ocurred:\n {err}")

async def main():
    await asyncio.gather(getrequest())
    print("Sleeping")
    await asyncio.sleep(10)
    print("2")

asyncio.run(main())

1 个答案:

答案 0 :(得分:2)

requests 不是异步的。

您不能在非异步响应上 await - 当它到达这些 await 之一时,您的代码将崩溃。

如果您需要异步 HTTP 客户端,请使用 aiohttphttpx

相关问题