AsyncIO Clients

Learn how AsyncIO simplifies client processes and concurrency with a marine weather forecast retrieval example.

Because it is capable of handling many thousands of simultaneous connections, AsyncIO is very common for implementing servers. However, it is a generic networking library and provides full support for client processes as well. This is pretty important, since many microservices act as clients to other servers.

Simplicity of clients

Clients can be much simpler than servers, as they don’t have to be set up to wait for incoming connections. We can leverage the await asyncio.gather() function to parcel out a lot of work, and wait to process the results when they’ve completed. This can work well with asyncio.to_thread() which assigns blocking requests to separate threads, permitting the main thread to interleave work among the coroutines.

We can also create individual tasks that can be interleaved by the event loop. This allows the coroutines that implement the tasks to cooperatively schedule reading data along with computing the data that was read.

Example

Here’s an application to make requests to the US weather service, implemented using asyncio. We’ll focus on forecast zones useful for sailors in the Chesapeake Bay area. We’ll start with some definitions:

Get hands-on with 1200+ tech skills courses.