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