Waiting for a future – async and await

We discussed how one could wait for data from a future inside a co-routine using await. We saw an example that uses await to yield control to other co-routines. Let's now look at an example that waits for I/O completion on a future, which returns data from the web.

For this example, you need the aiohttp module which provides an HTTP client and server to work with the asyncio module and supports futures. We also need the async_timeout module which allows timeouts on asynchronous co-routines. Both these modules can be installed using pip.

Here is the code—this is a co-routine that fetches a URL using a timeout and awaits the future, that is, the result of the operation:

# async_http.py import asyncio import aiohttp ...

Get Software Architecture with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.