-1

There is my code down below. I don't understand one thing. Since I removed await keyword for both below lines:

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

I expected to see in output immediately :

Requesting response1...
Requesting response2...

Nevertheless i only see when program runs:

Requesting response1...

While its processing request1 nevertheless to me second text should be printed. Why it works like that?

My code:

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())
Henry
  • 537
  • 1
  • 9
  • 22
  • Does this answer your question? [How could I use requests in asyncio?](https://stackoverflow.com/questions/22190403/how-could-i-use-requests-in-asyncio) – Gino Mempin May 28 '21 at 10:02
  • 3
    And you shouldn't be using internal `pip._vendor`. Install the actual [requests](https://stackoverflow.com/q/22190403/2745495) library for your own app/script. – Gino Mempin May 28 '21 at 10:04

1 Answers1

2

requests is not async.

You can't await on a non-async response – your code will crash when it reaches one of those awaits.

Use aiohttp or httpx if you need an async HTTP client.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • hmm i am the suprised why then when putting await before; session.post(.. not giving syntax error or something. – Henry May 28 '21 at 10:13
  • 1
    Well, considering there's a stray `}` in your original code too, you've clearly edited things before posting here, so I can't quite believe you there. – AKX May 28 '21 at 10:16
  • There's not. I've just edited quickly therefore }. – Henry May 28 '21 at 10:18