I am following the code in this page: https://www.twilio.com/en-us/blog/asynchronous-http-requests-in-python-with-aiohttp.
Here is the first approach using aiohttp
:
import aiohttp
import asyncio
import time
start_time = time.time()
async def main():
async with aiohttp.ClientSession() as session:
for num in range(1, 10):
pokemon_url = f'https://pokeapi.co/api/v2/pokemon/{num}'
async with session.get(pokemon_url) as response:
pokemon_json = await response.json()
print(pokemon_json['name'], num)
asyncio.run(main())
print(f'{time.time() - start_time} seconds')
If I understand it correctly, the for loop executes session.get
synchronously thus the GET request are sent out sequentially. Asynchronous Programming is not giving ertra performance benefits here.
Approach 2 is the regular approach using requests
. It’s also executed synchronously:
import requests
import time
start_time = time.time()
for num in range(1, 10):
url = f'https://pokeapi.co/api/v2/pokemon/{num}'
response = requests.get(url)
pokemon = response.json()
print(pokemon['name'])
print(f'{time.time() - start_time} seconds')
The approach 1 took 3.581976890563965 seconds. Approach 2 took 8.428680419921875 seconds. Since they both executes GET requests sequentially, what’s the reason for approach 1
using aiohttp
still being faster than requests
?