3.1 - Example: Simulated Network Call
Enroll to start learning
Youβve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.
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.