Last active
December 4, 2025 01:35
-
-
Save Lily418/adea074e82683b12b3728290d625910c to your computer and use it in GitHub Desktop.
Demonstration of using async http requests in Python
This file contains hidden or 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 | |
| import time | |
| import requests | |
| import aiohttp | |
| def do_work(): | |
| response = requests.get("https://youdosudoku.com/api/") | |
| if response.status_code == 200: | |
| data = response.json() | |
| print(".", end='', flush=True) | |
| else: | |
| print(f"Error: {response.status_code}") | |
| async def do_work_async(session): | |
| response = await session.get("https://youdosudoku.com/api/") | |
| if response.status == 200: | |
| data = await response.json() | |
| print(".", end='', flush=True) | |
| else: | |
| print(f"Error: {response.status_code}") | |
| def synchronous(iterations): | |
| start_time = time.monotonic() | |
| for i in range(0,iterations): | |
| do_work() | |
| end_time = time.monotonic() | |
| print(str(iterations) + " iterations in " + str(round(end_time-start_time, 2)) + " seconds") | |
| async def asynchronous(iterations): | |
| start_time = time.monotonic() | |
| tasks = [] | |
| conn = aiohttp.TCPConnector(limit_per_host=2) | |
| async with aiohttp.ClientSession(connector=conn) as session: | |
| for i in range(0,iterations): | |
| tasks.append(do_work_async(session)) | |
| await asyncio.gather(*tasks) | |
| end_time = time.monotonic() | |
| print(str(iterations) + " iterations in " + str(round(end_time-start_time, 2)) + " seconds") | |
| iterations = 20 | |
| asyncio.run(asynchronous(iterations)) | |
| synchronous(iterations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment