Async layer
- Python course
- Advanced
- Lesson 80/83
- 6 min
Set up data flow with async/await and aiohttp.
Async layer
The second layer uses asyncio.gather to fetch from multiple sources concurrently. gather awaits all the coroutines it receives and returns their results as a list.
async def fetch_all():
return await asyncio.gather(
fetch_tasks(), fetch_tasks()
)Here fetch_tasks is called twice; gather runs them concurrently. In the real world this is like querying two HTTP sources in parallel; the total time is the slowest call.
gather and await
gather returns a coroutine; you need await to get the result. Without await you keep a coroutine object; the function's result is never obtained.
async def fetch_all():
return await asyncio.gather(
fetch_tasks(), fetch_tasks()
)Each call is a separate source; gather returns when all of them finish. This pattern is the core advantage of async for speeding up many I/O jobs.
Practice Add the fetch_all function
The starting code contains the previous lesson's fetch_tasks solution. Add an async def fetch_all(): function whose body does return await asyncio.gather(fetch_tasks(), fetch_tasks()). Then print the result with print(asyncio.run(fetch_all())).
Starter code
import asyncio
async def fetch_tasks():
return [{"id": 1, "title": "Görev 1"}, {"id": 2, "title": "Görev 2"}]
# define an async function named fetch_all
# call fetch_tasks twice via asyncio.gather and await it
# run fetch_all with asyncio.run and print the resultSample solution
import asyncio
async def fetch_tasks():
return [{"id": 1, "title": "Görev 1"}, {"id": 2, "title": "Görev 2"}]
async def fetch_all():
return await asyncio.gather(fetch_tasks(), fetch_tasks())
print(asyncio.run(fetch_all()))Expected output
[[{'id': 1, 'title': 'Görev 1'}, {'id': 2, 'title': 'Görev 2'}], [{'id': 1, 'title': 'Görev 1'}, {'id': 2, 'title': 'Görev 2'}]]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does asyncio.gather(fetch_tasks(), fetch_tasks()) return?
- A list of two lists Correct answer
- A single list
- A coroutine
- An error
Explanation: gather puts each call's result in order; two lists come back.
2 Complete the gather call
async def fetch_all():
return await asyncio.____(fetch_tasks(), fetch_tasks())
async def fetch_all():
return await asyncio.gather(fetch_tasks(), fetch_tasks())
Explanation: gather awaits coroutines concurrently.
3 Match the async layer concepts
| Term | Meaning |
|---|---|
gather |
Awaits concurrently |
await |
Unwraps the result |
fetch_all |
Multi-source function |
asyncio.run |
Starts the event loop |