Example: Simulated Network Call - 3.1 | Chapter 8: Asynchronous Programming with asyncio | Python Advance
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

Simulate network delay

print(f"Completed fetch from {site_name}")
return f"Data from {site_name}"

async def main():
sites = ['api1.example.com', 'api2.example.com', 'api3.example.com']
tasks = [fetch_data(site) for site in sites]
results = await asyncio.gather(*tasks)
print("All data fetched:", results)

asyncio.run(main())

Explanation:
fetch_data() mimics a network call with random delay.

Multiple fetches run concurrently thanks to asyncio.gather().

The event loop runs until all tasks complete.

Practical Use Cases
Testing asynchronous workflows before integrating real APIs.

Simulating multiple users making requests concurrently.

Building prototypes of asynchronous client-server communication.


​​Question: Write an asynchronous function simulate_download that takes a file name and simulates downloading it by waiting a random time between 2 and 5 seconds. Then print a message indicating the file has been downloaded.

Answer:

import asyncio
import random

async def simulate_download(filename):
delay = random.uniform(2, 5)
print(f"Downloading {filename} (will take {delay:.2f} seconds)...")
await asyncio.sleep(delay)
print(f"Downloaded {filename}")

Usage example

asyncio.run(main())

Hint: Use asyncio.as_completed to handle tasks as they finish and try-except blocks to catch errors.