SlideShare a Scribd company logo
1 of 29
Download to read offline
Asynchronous Python
and You
A guide by Dayne Jones
dir(Dayne)
Iโ€™m Dayne. I try to make martech better.
Itinerary
I. A bit about AddShoppers
II. What is asynchronous
programming?
A. In general
B. In python
III. Why does it matter?
A. Are there benefits?
B. Is it worth using?
IV. How do I use it?
A. Which libraries should I use?
B. What kind of support can I
expect?
V. Demo
How are we using
asynchronous Python at
AddShoppers?
AddShoppers
โ— ### million requests per day, ####
rps
โ— Hanes, American Giant, Jockey,
more
โ— ## app servers (all tornado), ## db,
## cache, ## queue
โ— ## data pipeline servicing ~ ### rps
(asyncio)
โ— Hiring? Yes, please.
What is asynchronous
programming anyways?
Sync vs. Async
โ— Synchronous code waits to
return
โ— Asynchronous code returns
immediately
# synchronous
response = requests.get(url)
print(response)
# asynchronous
def print_resp(response):
print(response)
async_requests.get(url, callback=print_resp)
How does it work?
Event Loopdef start(self):
[...]
try:
while True:
[...]
while self._events:
fd, events = self._events.popitem()
try:
fd_obj, handler_func = self._handlers[fd]
handler_func(fd_obj, events)
except (OSError, IOError) as e:
[...]
except Exception:
self.handle_callback_exception(self._handlers.get(fd))
fd_obj = handler_func = None
Event Loop
def sync_handler(url):
response = requests.get(url) # takes 1 second
return response.status_code
def async_handler(url):
def print_resp(response):
return response.status_code
async_requests.get(url, callback=print_resp) # takes 1 second
Synchronous Asynchronous
1 Thread Available
1s
2s
3s
4s
5s
6s
1 Request
1s
2s
3s
4s
5s
6s
Synchronous Asynchronous
5 Threads Available
1s
2s
3s
4s
5s
6s
1 Request
1s
2s
3s
4s
5s
6s
Event-loop (continued)
โ— The CPU very often context switches at non deterministic intervals.
โ— Allows the programmer to mark context switches
โ— Single threaded (donโ€™t use synchronous code in your thread)
Common Patterns
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
http.fetch("http://my-api.com/v2/users", callback=self.on_response)
def on_response(self, response):
if response.error: raise tornado.web.HTTPError(500)
json = tornado.escape.json_decode(response.body)
self.write("Fetched " + str(len(json["entries"])) + "users from the API")
self.finish()
Callbacks
Futures/Coroutines
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
response = yield http.fetch("http://my-api.com/v2/users")
json = tornado.escape.json_decode(response.body)
self.write("Fetched " + str(len(json["entries"])) + " users from the API")
# Python 3.5
async def fetch_coroutine(url):
response = await some_async_function()
return response.body
# Tornado 4.3, Python 3.5
async def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
return response.body
Async/Await
Why do I want to use
asynchronous python?
# synchronous
response = requests.get(url) # takes 1 second
print(response)
# asynchronous
def print_resp(response):
print(response)
async_requests.get(url, callback=print_resp) # still takes 1 second
Efficiency
Real-time web
โ— Long lived connections
โ— Mostly idle
Common Use Cases
โ— Real-time web. Anything that requires long lived, mostly idle connections from
users.
โ— Network I/O. Waiting for HTTP requests to return.
โ— Database calls. Waiting for a database to return a query.
โ— Filesystem. Waiting for a disk.
โ— Anything else non CPU bound.
How do I write asynchronous
programs in Python?
Libraries
โ— Tornado Web
โ— asyncio
โ— Twisted (Event driven networking engine)
โ— Gevent (Networking library)
โ— Cyclone (Tornado API on top of Twisted)
Python 2.x, <= 3.3
โ— Tornado
โ—‹ Callbacks
โ—‹ Coroutines (generators)
โ— Gevent
โ— Twisted
โ— Cyclone
# Python 2
class MyHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(โ€œhttp://url.com")
return response
Python >= 3.3, < 3.5
โ— Tornado
โ—‹ Asyncio bridge library
โ—‹ Callbacks
โ—‹ Coroutines
โ— Asyncio
โ—‹ Coroutines (generators)
# Tornado
class MyHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(โ€œhttp://url.com"
return response
# asyncio
import asyncio
import aiohttp
@asyncio.coroutine
def fetch_page(url):
response = yield from aiohttp.request('GET', url)
assert response.status == 200
content = yield from response.read()
print('URL: {0}: Content: {1}'.format(url, content))
Python >= 3.5
โ— Tornado
โ—‹ async/await
โ— Asyncio
โ—‹ async/await
# Tornado
class MyHandler(tornado.web.RequestHandler):
async def get(self):
http_client = AsyncHTTPClient()
url = 'http://myurl.com'
response = await http_client.fetch(url)
return response
# asyncio
import asyncio
import aiohttp
@asyncio.coroutine
def fetch_page(url):
response = yield from aiohttp.request('GET', url)
assert response.status == 200
content = yield from response.read()
print('URL: {0}: Content: {1}'.format(url, content))
Miscellaneous
โ— Database driver (motor, Momoko)
โ— Redis
โ— Reading files
DEMO
Questions?

More Related Content

Similar to Asynchronous Python and You

C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingPraveen Prajapati
ย 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPMykola Novik
ย 
Highly concurrent yet natural programming
Highly concurrent yet natural programmingHighly concurrent yet natural programming
Highly concurrent yet natural programmingInfinit
ย 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with PythonSkoobe
ย 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with PythonAnton Caceres
ย 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#Ahasanul Kalam Akib
ย 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile AppsCraig Dunn
ย 
Motion Django Meetup
Motion Django MeetupMotion Django Meetup
Motion Django MeetupMike Malone
ย 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
ย 
Py4 inf 01-intro
Py4 inf 01-introPy4 inf 01-intro
Py4 inf 01-introIshaq Ali
ย 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringScyllaDB
ย 
Real time web
Real time webReal time web
Real time webMedhat Dawoud
ย 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrencyRuslan Novikov
ย 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problemJose Galarza
ย 
Rundown of Async/Await in Rust
Rundown of Async/Await in RustRundown of Async/Await in Rust
Rundown of Async/Await in RustKnoldus Inc.
ย 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ CoroutinesSumant Tambe
ย 
Summer training report priyanka
Summer  training  report priyankaSummer  training  report priyanka
Summer training report priyankapriyanka kumari
ย 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]Adam Englander
ย 

Similar to Asynchronous Python and You (20)

C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
ย 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
ย 
Highly concurrent yet natural programming
Highly concurrent yet natural programmingHighly concurrent yet natural programming
Highly concurrent yet natural programming
ย 
Asynctasks
AsynctasksAsynctasks
Asynctasks
ย 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with Python
ย 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with Python
ย 
py4inf-01-intro.ppt
py4inf-01-intro.pptpy4inf-01-intro.ppt
py4inf-01-intro.ppt
ย 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
ย 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
ย 
Motion Django Meetup
Motion Django MeetupMotion Django Meetup
Motion Django Meetup
ย 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
ย 
Py4 inf 01-intro
Py4 inf 01-introPy4 inf 01-intro
Py4 inf 01-intro
ย 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
ย 
Real time web
Real time webReal time web
Real time web
ย 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
ย 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problem
ย 
Rundown of Async/Await in Rust
Rundown of Async/Await in RustRundown of Async/Await in Rust
Rundown of Async/Await in Rust
ย 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
ย 
Summer training report priyanka
Summer  training  report priyankaSummer  training  report priyanka
Summer training report priyanka
ย 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]
ย 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
ย 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธanilsa9823
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
ย 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
ย 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
ย 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto Gonzรกlez Trastoy
ย 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...OnePlan Solutions
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
ย 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
ย 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
ย 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
ย 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
ย 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online  โ˜‚๏ธ
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Kakori Lucknow best sexual service Online โ˜‚๏ธ
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
ย 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ย 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
ย 
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female serviceCALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
CALL ON โžฅ8923113531 ๐Ÿ”Call Girls Badshah Nagar Lucknow best Female service
ย 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
ย 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
ย 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlanโ€™s ...
ย 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
ย 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
ย 
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS LiveVip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida โžก๏ธ Delhi โžก๏ธ 9999965857 No Advance 24HRS Live
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
ย 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
ย 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
ย 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
ย 

Asynchronous Python and You

  • 1. Asynchronous Python and You A guide by Dayne Jones
  • 2. dir(Dayne) Iโ€™m Dayne. I try to make martech better.
  • 3. Itinerary I. A bit about AddShoppers II. What is asynchronous programming? A. In general B. In python III. Why does it matter? A. Are there benefits? B. Is it worth using? IV. How do I use it? A. Which libraries should I use? B. What kind of support can I expect? V. Demo
  • 4. How are we using asynchronous Python at AddShoppers?
  • 5. AddShoppers โ— ### million requests per day, #### rps โ— Hanes, American Giant, Jockey, more โ— ## app servers (all tornado), ## db, ## cache, ## queue โ— ## data pipeline servicing ~ ### rps (asyncio) โ— Hiring? Yes, please.
  • 7. Sync vs. Async โ— Synchronous code waits to return โ— Asynchronous code returns immediately # synchronous response = requests.get(url) print(response) # asynchronous def print_resp(response): print(response) async_requests.get(url, callback=print_resp)
  • 8. How does it work?
  • 9. Event Loopdef start(self): [...] try: while True: [...] while self._events: fd, events = self._events.popitem() try: fd_obj, handler_func = self._handlers[fd] handler_func(fd_obj, events) except (OSError, IOError) as e: [...] except Exception: self.handle_callback_exception(self._handlers.get(fd)) fd_obj = handler_func = None Event Loop
  • 10. def sync_handler(url): response = requests.get(url) # takes 1 second return response.status_code def async_handler(url): def print_resp(response): return response.status_code async_requests.get(url, callback=print_resp) # takes 1 second
  • 11. Synchronous Asynchronous 1 Thread Available 1s 2s 3s 4s 5s 6s 1 Request 1s 2s 3s 4s 5s 6s
  • 12. Synchronous Asynchronous 5 Threads Available 1s 2s 3s 4s 5s 6s 1 Request 1s 2s 3s 4s 5s 6s
  • 13. Event-loop (continued) โ— The CPU very often context switches at non deterministic intervals. โ— Allows the programmer to mark context switches โ— Single threaded (donโ€™t use synchronous code in your thread)
  • 15. class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://my-api.com/v2/users", callback=self.on_response) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + "users from the API") self.finish() Callbacks
  • 16. Futures/Coroutines class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://my-api.com/v2/users") json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " users from the API")
  • 17. # Python 3.5 async def fetch_coroutine(url): response = await some_async_function() return response.body # Tornado 4.3, Python 3.5 async def fetch_coroutine(url): http_client = AsyncHTTPClient() response = await http_client.fetch(url) return response.body Async/Await
  • 18. Why do I want to use asynchronous python?
  • 19. # synchronous response = requests.get(url) # takes 1 second print(response) # asynchronous def print_resp(response): print(response) async_requests.get(url, callback=print_resp) # still takes 1 second Efficiency
  • 20. Real-time web โ— Long lived connections โ— Mostly idle
  • 21. Common Use Cases โ— Real-time web. Anything that requires long lived, mostly idle connections from users. โ— Network I/O. Waiting for HTTP requests to return. โ— Database calls. Waiting for a database to return a query. โ— Filesystem. Waiting for a disk. โ— Anything else non CPU bound.
  • 22. How do I write asynchronous programs in Python?
  • 23. Libraries โ— Tornado Web โ— asyncio โ— Twisted (Event driven networking engine) โ— Gevent (Networking library) โ— Cyclone (Tornado API on top of Twisted)
  • 24. Python 2.x, <= 3.3 โ— Tornado โ—‹ Callbacks โ—‹ Coroutines (generators) โ— Gevent โ— Twisted โ— Cyclone # Python 2 class MyHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch(โ€œhttp://url.com") return response
  • 25. Python >= 3.3, < 3.5 โ— Tornado โ—‹ Asyncio bridge library โ—‹ Callbacks โ—‹ Coroutines โ— Asyncio โ—‹ Coroutines (generators) # Tornado class MyHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch(โ€œhttp://url.com" return response # asyncio import asyncio import aiohttp @asyncio.coroutine def fetch_page(url): response = yield from aiohttp.request('GET', url) assert response.status == 200 content = yield from response.read() print('URL: {0}: Content: {1}'.format(url, content))
  • 26. Python >= 3.5 โ— Tornado โ—‹ async/await โ— Asyncio โ—‹ async/await # Tornado class MyHandler(tornado.web.RequestHandler): async def get(self): http_client = AsyncHTTPClient() url = 'http://myurl.com' response = await http_client.fetch(url) return response # asyncio import asyncio import aiohttp @asyncio.coroutine def fetch_page(url): response = yield from aiohttp.request('GET', url) assert response.status == 200 content = yield from response.read() print('URL: {0}: Content: {1}'.format(url, content))
  • 27. Miscellaneous โ— Database driver (motor, Momoko) โ— Redis โ— Reading files
  • 28. DEMO