SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Ähnlich wie Asynchronous Python Guide for Efficiency

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 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
 
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.
 
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
 

Ähnlich wie Asynchronous Python Guide for Efficiency (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]
 

Kürzlich hochgeladen

Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Kürzlich hochgeladen (20)

Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

Asynchronous Python Guide for Efficiency

  • 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