Last active
December 14, 2023 17:16
-
-
Save jsatt/16bcfc1b649a7ab1b568b037457b404f to your computer and use it in GitHub Desktop.
Samples of various asyncio patterns to understand how it works.
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 asyncio | |
from time import time | |
from httpx import AsyncClient | |
async def async_request(url: str): | |
async with AsyncClient() as client: | |
resp = await client.get(url) | |
result = len(resp.read()) | |
print(url) | |
return f'{url} - {result} - {resp.elapsed}' | |
async def sync_sample(): | |
print('run synchronously') | |
res1 = await async_request('https://google.com') | |
res2 = await async_request('https://amazon.com') | |
res3 = await async_request('https://jsatt.com') | |
print(res1, res2, res3) | |
async def create_task_sample(): | |
print('run concurrently using `asyncio.create_task`') | |
task1 = asyncio.create_task(async_request('https://google.com')) | |
task2 = asyncio.create_task(async_request('https://amazon.com')) | |
task3 = asyncio.create_task(async_request('https://jsatt.com')) | |
res1 = await task1 | |
res2 = await task2 | |
res3 = await task3 | |
print(res1, res2, res3) | |
async def gather_sample(): | |
print('run concurrently using `asyncio.gather`') | |
res1, res2, res3 = await asyncio.gather( | |
async_request('https://google.com'), | |
async_request('https://amazon.com'), | |
async_request('https://jsatt.com'), | |
) | |
print(res1, res2, res3) | |
async def runner(): | |
t1 = time() | |
# await sync_sample() | |
# await gather_sample() | |
await create_task_sample() | |
print(time() - t1) | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(runner()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More on asyncio