A good use of asyncio in python and django.

In this article, I pick a asynchronous programming concept from python which is launched in python 3.4. It provides infrastructure for writing single-threading concurrent code using coroutines and it is totally based on event loop.

The basic terminology used-

  1. Coroutine :-

This is a sequence of instruction or a simply function which is used for specific task but difference between simple function and coroutine is that coroutine can pause and resume that’s why coroutine can be used for non-primitive multi-tasking.

In python, Coroutine like generator but difference between coroutine and generator is that generator produce data but coroutine consume data.

coroutine is define in two way -

A. Using async def which is given in 3.5 -

B. By using @asyncio.coroutine decorator (generator based)-

We have to use this decorator @asyncio.coroutine to define coroutine.

2. Task -

It is scheduler for coroutine. A Task is a subclass of Future that wraps a coroutine and Future is an object that is supposed to have a result in the future.

3. Event loop -

It as the central executor in asyncio. It is like javascript, nodejs, nginx’s event loop etc.

something like -

Simple use case :-

  1. web scraping -

Web scraping automatically extracts data and presents it in a format you can access easily.

Key Points to remember-

  1. Firstly, You should check website’s terms and condition before scrape.
  2. Do not hit more request simultaneously because this may break the website. Below my example show only basic use, You can use asyncio for hit multiple website together.
  3. The layout of a website may change from time to time, so make sure to revisit the site and rewrite your code as needed.

Note:- This is only example how to use asyncio. you should not be used data for commercial purposes.

2. In django project -

Let suppose you want to send mail/bulk send then you never want toend users to have to wait unnecessarily. In this case we can use asyncio-