Before we start we need to ask a few questions.
- Why do we use Asyncio?
- Where do we use asyncio?
- How do we use asyncio?
1. Why do we use Aysncio?
Python has been around for decades in the synchronous world. You call functions directly and everything gets processed as it’s written on the screen. Your only built-in option for running code in parallel in the same process is threads. When it comes to building web servers with python, this doesn't work because web servers should deal with many requests coming from different clients and servers should deal with these requests parallelly (asynchronously). Hence synchronous way is not the option. So to solve this we have a library in python called asyncio which gives us the flexibility to build servers and handle requests parallelly without the need for threads.
2. Where do we use Asyncio?
Asyncio is mainly used for building web servers with python. As explained above, when a request is made from the client to the server, we can’t have the server wait for that request to be processed, holding back other requests from different clients in pending state. The idea behind asynchronous is processing the remaining requests and sending back the response accordingly, while some requests require more time to be processed.
3. How do we use Asyncio?
3.1 Events Loops
The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.
Here we are referring to the currently running event loop.
3.2 Async/await syntax
Let’s see an example where we can print “Hello World” with some delay.
The async keyword notifies that the delayedHelloWorld function is a coroutine. Which can be awaited in other coroutines. For example, here we are awaiting delayedHelloWorld inside the main coroutine with
await delayedHelloWorld(2) . In the end, we can just tweak our code a little bit and make it look compact by deleting
loop = asyncio.get_event_loop() and
loop.run_until_complete(main()) and replacing them with
4. Mocking a webserver
As we know the required basics for writing an asyncio application, let’s imitate a webserver.
Here we are making 2 requests to the server
request_2 . Both requests are coroutines. Let’s assume these 2 requests are from 2 different clients. So we gather the requests and process them concurrently. In the output, we can see that
request_1 is queued first for processing and then
request_2 is queued.
request_1 requires 2 seconds to process and
request_2 requires only 1 second. Hence
request_2 will be processed first without waiting for
request_1to be processed. Hence asynchronous is achieved.
Hope you enjoyed this article!
Let me know your thoughts and comments below, and until next time! :P