A good use of asyncio in python and django.

Gaurav Balyan
Dec 17, 2017 · 3 min read

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 -

Image for post
Image for post

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

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

Image for post
Image for post

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.

Image for post
Image for post

3. Event loop -

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

something like -

Image for post
Image for post

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.
Image for post
Image for post

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-

Image for post
Image for post

Thanks.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store