O'Reilly logo

Software Architecture with Python by Anand Balachandran Pillai

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required