SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
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?

Contenu connexe

Similaire à 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 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
 

Similaire à 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]
 

Dernier

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
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
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 

Dernier (20)

%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
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...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 

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