Testing asynchronous code
Our first example will show two tasks that are going to run concurrently. One will extract some data from the Nobel Prize laureates REST API and the other will simulate a printing job for documents (source code available at Chapter 6/concurrent_tasks.py):
import asyncio
import aiohttp
URL = "https://api.nobelprize.org/2.1/laureate/"
async def get_nobel_facts(nid):
print("Starting nobel extraction")
await asyncio.sleep(5)
async with aiohttp.ClientSession() as session:
async with session.get(URL + str(nid)) as response:
if response.status == 200:
nobel = await response.json()
print(nobel[0]["knownName"]["en"])
async def print_document(doc_name, sleep_time):
print(f"[{time.strftime('%X')}] Print '{doc_name}'...")
await asyncio.sleep(sleep_time)
print(f"[{time.strftime('%X')}] Finished.")
async...