Created
March 25, 2021 17:15
-
-
Save PhanDuc/ccc0c7d9278bd4b043f8561fe7f808ee to your computer and use it in GitHub Desktop.
Asyncio get request using aiohttp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aiohttp | |
import asyncio | |
import time | |
import requests | |
from PIL import Image | |
import io | |
start_time = time.time() | |
urls = [ | |
"https://kscloset.vn/wp-content/uploads/2021/03/K154TES-FK1AADOOK116TES-FK5A0CAM1--270x370.jpg", | |
"https://kscloset.vn/wp-content/uploads/2021/03/K054ONS-FK4AGTSA--270x370.jpg", | |
"https://kscloset.vn/wp-content/uploads/2021/03/K052TES-BK1ACHON-K078TES-FT5BKDAM1--270x370" | |
".jpg", | |
"https://kscloset.vn/wp-content/uploads/2021/03/K044ONS-DK3BAXAN2--270x370.jpg", | |
"https://kscloset.vn/wp-content/uploads/2021/03/K028ONS-FT1CCXANK012ONS-FT2BDXAN--270x370.jpg" | |
] | |
async def get_pokemon(session, url): | |
async with session.get(url) as resp: | |
pokemon = await resp.read() | |
# return pokemon["name"] | |
return pokemon | |
async def main(): | |
results = dict() | |
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session: | |
tasks = [] | |
# for number in range(1, 20): | |
for ind, url in enumerate(urls): | |
# url = f'https://pokeapi.co/api/v2/pokemon/{number}' | |
tasks.append(asyncio.ensure_future(get_pokemon(session, url))) | |
results[ind] = url | |
original_pokemon = await asyncio.gather(*tasks) | |
pil_image = [pokemon for pokemon in original_pokemon] | |
for ind, pokemon in enumerate(pil_image): | |
print(results[ind]) | |
pil_image = Image.open(io.BytesIO(pokemon)).convert("RGB") | |
pil_image.save(f"/media/Entertaiment/{ind}.jpg") | |
# print(pokemon) | |
asyncio.run(main()) | |
print("--- %s seconds ---" % (time.time() - start_time)) | |
start_time = time.time() | |
# for number in range(1, 20): | |
# url = f'https://pokeapi.co/api/v2/pokemon/{number}' | |
# resp = requests.get(url) | |
# pokemon = resp.json() | |
# print(pokemon['name']) | |
# | |
# print("--- %s seconds ---" % (time.time() - start_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment