SlideShare a Scribd company logo
1 of 18
Asynchronous programming
with Django
Why Integrating asynchronous frameworks into
django
Synchronous vs Asynchronous
• Synchronous Execution
• My boss is a busy man. He tells me to write the code. I tell him: Fine. I get
started and he's watching me like a vulture, standing behind me, off my
shoulder. I'm like "Dude, WTF: why don't you go and do something while I
finish this?"
• he's like: "No, I'm waiting right here until you finish." This is synchronous.
• Asynchronous Execution
• The boss tells me to do it, and rather than waiting right there for my work,
the boss goes off and does other tasks. When I finish my job I simply report
to my boss and say: "I'm DONE!" This is Asynchronous Execution.
Source:stackoverflow
Lets take a real world example to justify the difference
• Django can perform all kind of CRUD operations but can perform a single
request one after one
• Lets take a real world example if I want to manipulate a data transmitted by a
user and perform a logic before adding it to database
def post(request): def get(request,data):
return data
if request.method==Post:
data=get(data)
if data is not None:
data.save()
Use cases of asynchronous programming
Use cases of asynchronous programming
Use cases of asynchronous programming
Python asynchronous frameworks
• Tornado
• Twisted
• Asyncio(aiohttp for server/client)
• And we will use aiohttp framework to make a part of my function
asynchronous
Basic asyncio knowledge before procceding to aiohttp
• >>> import asyncio
• >>> async def main():
• ... print('hello')
• ... await asyncio.sleep(1)
• ... print('world')
• >>> asyncio.run(main())
• hello
• world
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
started at 17:13:52
hello
world
finished at 17:13:55
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
started at 17:14:32
hello
world
finished at 17:14:34
Now lets have a greater understanding on how all this things works and how are going to
use the response generated from Django and perform our logic and then submitting this to
database
By creating a asynchronous functions using AIOHTTP
We will just create a simple otp function when ever a user signsup the user will be asked to
verify his otp so that his otp gets verified and he will be added to the database
Basic knowledge on aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(resp.status)
print(await resp.text())
• session.put('http://httpbin.org/put', data=b'data') session.delete('http://httpbin.org/delete’)
• session.head('http://httpbin.org/get’)
• session.options('http://httpbin.org/get’)
• session.patch('http://httpbin.org/patch', data=b'data')
async def index(request):
async with aiohttp.ClientSession() as client:
data=await(email_sending(client))
print(data)
await
client.post('http://127.0.0.1:8000/acc/signup/',data=data)
return web.Response(text="OK")
async with aiohttp.ClientSession() a
async def email_sending(client):
async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp:
resp=await(resp.json())
totp = pyotp.TOTP('base32secret3232')
otp=totp.now()
smtp.sendmail("you@gmail.com",resp['email'], otp)
sucess=asyncio.create_task(email_verification(otp))
return resp
async def email_verification(otp):
otp=otp
print(otp)
await asyncio.sleep(30)
async with aiohttp.ClientSession() as client:
async with client.get('httxp://localhost:3000/employees') as v_otp:
v_otp=await(v_otp.json())
print(v_otp)
async def index(request):
async with aiohttp.ClientSession() as client:
data=await(email_sending(client))
print(data)
await client.post('http://127.0.0.1:8000/acc/signup/',data=data)
return web.Response(text="OK")
async def email_sending(client):
async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp:
resp=await(resp.json())
totp = pyotp.TOTP('base32secret3232')
otp=totp.now()
smtp.sendmail("you@gmail.com",resp['email'], otp)
sucess=asyncio.create_task(email_verification(otp))
return resp
async def email_verification(otp):
otp=otp
print(otp)
await asyncio.sleep(30)
async with aiohttp.ClientSession() as client:
async with client.get('httxp://localhost:3000/employees') as v_otp:
v_otp=await(v_otp.json())
print(v_otp)

More Related Content

Similar to Asynchronous programming with django

An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Cloudflare
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
Cloudflare
 
node.js workshop- JavaScript Async
node.js workshop- JavaScript Asyncnode.js workshop- JavaScript Async
node.js workshop- JavaScript Async
Qiong Wu
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 

Similar to Asynchronous programming with django (20)

JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Coding in the context era
Coding in the context eraCoding in the context era
Coding in the context era
 
node.js workshop- JavaScript Async
node.js workshop- JavaScript Asyncnode.js workshop- JavaScript Async
node.js workshop- JavaScript Async
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
Tulip
TulipTulip
Tulip
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
4. Interaction
4. Interaction4. Interaction
4. Interaction
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java Developers
 
From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017From Elixir to Akka (and back) - ElixirConf Mx 2017
From Elixir to Akka (and back) - ElixirConf Mx 2017
 
While loop
While loopWhile loop
While loop
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Seu primeiro loop com Python AsyncIO - TDC 2016
Seu primeiro loop com Python AsyncIO - TDC 2016Seu primeiro loop com Python AsyncIO - TDC 2016
Seu primeiro loop com Python AsyncIO - TDC 2016
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Asynchronous programming with django

  • 2. Why Integrating asynchronous frameworks into django
  • 3. Synchronous vs Asynchronous • Synchronous Execution • My boss is a busy man. He tells me to write the code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?" • he's like: "No, I'm waiting right here until you finish." This is synchronous. • Asynchronous Execution • The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution. Source:stackoverflow
  • 4. Lets take a real world example to justify the difference • Django can perform all kind of CRUD operations but can perform a single request one after one • Lets take a real world example if I want to manipulate a data transmitted by a user and perform a logic before adding it to database def post(request): def get(request,data): return data if request.method==Post: data=get(data) if data is not None: data.save()
  • 5. Use cases of asynchronous programming
  • 6. Use cases of asynchronous programming
  • 7. Use cases of asynchronous programming
  • 8. Python asynchronous frameworks • Tornado • Twisted • Asyncio(aiohttp for server/client) • And we will use aiohttp framework to make a part of my function asynchronous
  • 9. Basic asyncio knowledge before procceding to aiohttp • >>> import asyncio • >>> async def main(): • ... print('hello') • ... await asyncio.sleep(1) • ... print('world') • >>> asyncio.run(main()) • hello • world
  • 10. import asyncio import time async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print(f"started at {time.strftime('%X')}") await say_after(1, 'hello') await say_after(2, 'world') print(f"finished at {time.strftime('%X')}") asyncio.run(main()) started at 17:13:52 hello world finished at 17:13:55
  • 11. async def main(): task1 = asyncio.create_task( say_after(1, 'hello')) task2 = asyncio.create_task( say_after(2, 'world')) print(f"started at {time.strftime('%X')}") # Wait until both tasks are completed (should take # around 2 seconds.) await task1 await task2 print(f"finished at {time.strftime('%X')}") started at 17:14:32 hello world finished at 17:14:34
  • 12. Now lets have a greater understanding on how all this things works and how are going to use the response generated from Django and perform our logic and then submitting this to database By creating a asynchronous functions using AIOHTTP We will just create a simple otp function when ever a user signsup the user will be asked to verify his otp so that his otp gets verified and he will be added to the database
  • 13. Basic knowledge on aiohttp async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text()) • session.put('http://httpbin.org/put', data=b'data') session.delete('http://httpbin.org/delete’) • session.head('http://httpbin.org/get’) • session.options('http://httpbin.org/get’) • session.patch('http://httpbin.org/patch', data=b'data')
  • 14.
  • 15. async def index(request): async with aiohttp.ClientSession() as client: data=await(email_sending(client)) print(data) await client.post('http://127.0.0.1:8000/acc/signup/',data=data) return web.Response(text="OK") async with aiohttp.ClientSession() a
  • 16. async def email_sending(client): async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp: resp=await(resp.json()) totp = pyotp.TOTP('base32secret3232') otp=totp.now() smtp.sendmail("you@gmail.com",resp['email'], otp) sucess=asyncio.create_task(email_verification(otp)) return resp
  • 17. async def email_verification(otp): otp=otp print(otp) await asyncio.sleep(30) async with aiohttp.ClientSession() as client: async with client.get('httxp://localhost:3000/employees') as v_otp: v_otp=await(v_otp.json()) print(v_otp)
  • 18. async def index(request): async with aiohttp.ClientSession() as client: data=await(email_sending(client)) print(data) await client.post('http://127.0.0.1:8000/acc/signup/',data=data) return web.Response(text="OK") async def email_sending(client): async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp: resp=await(resp.json()) totp = pyotp.TOTP('base32secret3232') otp=totp.now() smtp.sendmail("you@gmail.com",resp['email'], otp) sucess=asyncio.create_task(email_verification(otp)) return resp async def email_verification(otp): otp=otp print(otp) await asyncio.sleep(30) async with aiohttp.ClientSession() as client: async with client.get('httxp://localhost:3000/employees') as v_otp: v_otp=await(v_otp.json()) print(v_otp)