SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
Python, do 
you even 
async? 
Saúl Ibarra Corretgé 
@saghul 
DomCode, August 2014
repr(self) 
>>> from Amsterdam import saghul 
>>> 
>>> saghul.work() 
VoIP, SIP, XMPP, chat, Real Time Communications 
>>> 
>>> saghul.other() 
networking, event loops, sockets, MOAR PYTHON 
>>> 
>>> saghul.languages() 
Python, C 
>>>
github.com/saghul
Please give feedback! 
https://joind.in/event/view/2471
The road to 
asynchronous i/o
import socket 
import socket 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
print("Server listening on: {}".format(server.getsockname())) 
! 
client, addr = server.accept() 
print("Client connected: {}".format(addr)) 
! 
while True: 
data = client.recv(4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data) 
! 
server.close()
except Exception: 
• We can only handle one client at a time! 
• Solutions for handling multiple clients 
• Threads 
• I/O multiplexing 
• Check the C10K problem if you haven’t 
already! 
• http://www.kegel.com/c10k.html
try: sockets + threads 
import socket 
import thread 
! 
def handle_client(client, addr): 
print("Client connected: {}".format(addr)) 
while True: 
data = client.recv(4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data.upper()) 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
print("Server listening on: {}".format(server.getsockname())) 
! 
while True: 
client, addr = server.accept() 
thread.start_new_thread(handle_client, (client, addr))
except Exception: 
• Threads have overhead 
• Stack size 
• Context switching 
• Synchronisation 
• GIL? 
• Not for I/O!
I/O multiplexing 
• Examine and block for I/O in multiple 
file descriptors at the same time 
• Single thread 
• A file descriptor is ready if the 
corresponding I/O operation can be 
performed without blocking 
• File descriptor has to be set to be 
non-blocking
I/O is hard 
• Different paradigms in Unix vs 
Windows 
• “are you ready?” vs “call me later” 
• Frameworks 
• Abstract platform differences 
• Provide tools for easier development of 
applications
The included batteries 
• select 
• asyncore / asyncchat 
• selectors 
• asyncio
“batteries don’t fit” 
http://bit.ly/182HcHT
Frameworks 
• Platform abstraction 
• Protocol implementations 
• Integration with other event loops: Qt, 
GLib, ... 
• Different API styles 
• Async file i/o?
import twisted 
• Uses select, poll, kqueue, epoll from 
the select module 
• IOCP on Windows 
• Integration with other event loops 
• Factory / Protocol / Transport 
abstractions 
• Deferreds
import tornado 
• Uses select, poll, kqueue, epoll from 
the select module 
• select() on Windows :-( 
• Mainly oriented to web development 
• Synchronous looking API with 
coroutines / Futures
import gevent 
• Uses libev for platform abstraction 
• select() on Windows :-( 
• Syncronous API using greenlet 
• ME LIKEY! :-)
Solution!
I’m not trying to reinvent the 
wheel. I’m trying to build a 
good one. 
! 
Guido van Rossum
asyncio 
import tulip
import asyncio 
• Reference implementation for 
PEP-3156 
• Basic components for doing async i/o 
• Works on Python >= 3.3 
• Trollius: backport for Python >= 2.6
Goals 
• Modern implementation of asynchronous 
i/o for Python 
• Use yield from (PEP-380) 
• But don’t force it 
• Don’t use anything that requires 
Python > 3.3 
• Interoperability with other frameworks
Goals 
• Unix and Windows support 
• IPv4 and IPv6 
• TCP, UDP and pipes 
• Basic SSL (secure by default) 
• Subprocesses
Non goals 
• Perfection 
• Replacing current frameworks 
• Protocol implementations 
• Replace httplib, smtplib, ... 
• Make it work on Python < 3.3
Interoperability 
twisted tornado gevent ... 
asyncio 
selectors iocp
Example: Tornado 
tornado 
asyncio / twisted 
tornado 
epoll/kqueue
Architecture
Components 
Event loop, policy 
Coroutines, Futures, Tasks 
Transports, Protocols, Streams
Calculate 
poll time Poll 
Run 
callbacks 
Event loop
Event loop & policy 
• Chooses the best i/o mechanism for a 
given platform 
• APIs for creating server and client 
connections (TCP, UDP, …) 
• Establish the context for a loop
Working with threads 
• loop.call_soon_threadsafe(func, *args) 
• loop.run_in_executor(exc, func, *args) 
• loop.set_default_executor(exc) 
! 
• PEP-3148 executor
Coroutines, Futures & 
Tasks
Coroutines, Futures & Tasks 
• Coroutines 
• a generator function, can receive values 
• decorated with @coroutine 
• Future 
• promise of a result or an error 
• Task 
• Future which runs a coroutine
Coroutines & yield from 
import asyncio 
import socket 
! 
loop = asyncio.get_event_loop() 
! 
@asyncio.coroutine 
def handle_client(client, addr): 
print("Client connected: {}".format(addr)) 
while True: 
data = yield from loop.sock_recv(client, 4096) 
if not data: 
print("Client has disconnected") 
break 
client.send(data) 
! 
@asyncio.coroutine 
def accept_connections(server_socket): 
while True: 
client, addr = yield from loop.sock_accept(server_socket) 
asyncio.async(handle_client(client, addr)) 
! 
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) 
server.bind(('127.0.0.1', 1234)) 
server.listen(511) 
server.setblocking(False) 
print("Server listening on: {}".format(server.getsockname())) 
! 
loop.run_until_complete(accept_connections(server))
Coroutines & yield from 
• Imagine the yield from is not there 
• Imagine the code is executed 
sequentially 
• Not exactly the formal definition of yield 
from (from PEP-380)
Futures 
• Similar to Futures from PEP-3148 
• API (almost) identical 
• Adapted for asyncio’s single threaded 
model
Futures + Coroutines 
• yield from works with Futures! 
• f = Future() 
• Someone will set the result or exception 
• r = yield from f 
• Waits until done and returns f.result() 
• Usually returned by functions
Undoing callbacks (I) 
@asyncio.coroutine 
def sync_looking_function(*args): 
fut = asyncio.Future() 
def cb(result, error): 
if error is not None: 
fut.set_result(result) 
else: 
fut.set_exception(Exception(error)) 
async_function(cb, *args) 
return (yield from fut)
Undoing callbacks (II) 
! 
def sync_looking_function(*args): 
fut = asyncio.Future() 
def cb(result, error): 
if error is not None: 
fut.set_result(result) 
else: 
fut.set_exception(Exception(error)) 
async_function(cb, *args) 
return fut
Tasks 
• Unicorns covered in fairy dust 
• It’s a coroutine wrapped in a Future 
• Inherits from Future 
• Works with yield from 
• r = yield from Task(coro(...))
Tasks vs coroutines 
• A coroutine doesn’t “advance” without 
a scheduling mechanism 
• Tasks can advance in their own 
• The event loop is the scheduler!
Example 
import asyncio 
! 
loop = asyncio.get_event_loop() 
clients = {} # task -> (reader, writer) 
! 
def accept_client(client_reader, client_writer): 
task = asyncio.Task(handle_client(client_reader, client_writer)) 
clients[task] = (client_reader, client_writer) 
! 
def client_done(task): 
del clients[task] 
! 
task.add_done_callback(client_done) 
! 
@asyncio.coroutine 
def handle_client(client_reader, client_writer): 
while True: 
data = (yield from client_reader.readline()) 
client_writer.write(data) 
!! 
f = asyncio.start_server(accept_client, '127.0.0.1', 12345) 
server = loop.run_until_complete(f) 
loop.run_forever()
Transports & Protocols
Transports & Protocols 
• Transport: represents a connection 
(socket, pipe, ...) 
• Protocol: represents an application 
(HTTP server, IRC client, ...) 
• They always go together 
• API is based on function calls and 
callbacks
Streams 
• Abstraction on top of transports / 
protocols 
• File-like API using coroutines
Transport -> Protocol 
• connection_made(transport) 
• data_received(data) 
• eof_received() 
• connection_lost(exc) 
! 
• UDP, pipes and subprocesses are slightly 
different
Protocol -> Transport 
• write(data) 
• writelines(seq) 
• write_eof() 
• close()
Enter Trollius! 
• Backport of asyncio for Python >= 2.6 
• By Victor Stinner (@haypo) 
• Slightly different syntax 
• yield instead of yield from 
• raise Return(x) instead of return x on 
generators 
• pip install trollius
That was all?! 
• Go read PEP-3156 
• Implement a simple protocol (an IRC 
client for example) 
• Checkout the links on the last slide 
• Use asyncio in your next project
Questions? 
@saghul 
bettercallsaghul.com
Links 
• https://code.google.com/p/tulip/ 
• http://legacy.python.org/dev/peps/ 
pep-3156/ 
• https://code.google.com/p/tulip/wiki/ 
ThirdParty 
• http://asyncio.org/ 
• http://www.slideshare.net/saghul

Mais conteúdo relacionado

Mais procurados

Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in PythonMosky Liu
 
Tornado web
Tornado webTornado web
Tornado webkurtiss
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Feihong Hsu
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsAnton Arhipov
 
Vert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDVert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDTim Nolet
 
Of Owls and IO Objects
Of Owls and IO ObjectsOf Owls and IO Objects
Of Owls and IO ObjectsFelix Morgner
 
Treasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportTreasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportRitta Narita
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programmingDima Malenko
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsGraham Dumpleton
 
Bucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductionBucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductiondshkolnikov
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk pptShahroz Khan
 
Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating languagejgrahamc
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the ServerDoug Jones
 

Mais procurados (20)

Concurrency in Python
Concurrency in PythonConcurrency in Python
Concurrency in Python
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Tornado web
Tornado webTornado web
Tornado web
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Event loop
Event loopEvent loop
Event loop
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
 
Oredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java AgentsOredev 2015 - Taming Java Agents
Oredev 2015 - Taming Java Agents
 
Async await
Async awaitAsync await
Async await
 
Vert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDVert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCD
 
Of Owls and IO Objects
Of Owls and IO ObjectsOf Owls and IO Objects
Of Owls and IO Objects
 
Treasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportTreasure Data Summer Internship Final Report
Treasure Data Summer Internship Final Report
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programming
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
Bucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introductionBucks County Tech Meetup: node.js introduction
Bucks County Tech Meetup: node.js introduction
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk ppt
 
Lua: the world's most infuriating language
Lua: the world's most infuriating languageLua: the world's most infuriating language
Lua: the world's most infuriating language
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 

Destaque

Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Geventemptysquare
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with geventMahendra M
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingAlex Derkach
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerGeek Advisor Freddy
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Agraj Mangal
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development processAndrii Soldatenko
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django ChannelsAlbert O'Connor
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?Andrii Soldatenko
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glueJiahao Chen
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and PythonAndrii Soldatenko
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in PythonRyan Johnson
 

Destaque (20)

Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Gevent
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data binding
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Python on Rails 2014
Python on Rails 2014Python on Rails 2014
Python on Rails 2014
 
Python class
Python classPython class
Python class
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
 
Python master class 3
Python master class 3Python master class 3
Python master class 3
 
Building microservices with vert.x 3.0
Building microservices with vert.x 3.0Building microservices with vert.x 3.0
Building microservices with vert.x 3.0
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development process
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django Channels
 
Regexp
RegexpRegexp
Regexp
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glue
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and Python
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
 

Semelhante a Python, do you even async?

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaYardena Meymann
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研vorfeed chen
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python AsyncioNathan Van Gheem
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileAmazon Web Services Japan
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Codemotion
 
What is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaWhat is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaEdureka!
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptsenthilnathans25
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''OdessaJS Conf
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 

Semelhante a Python, do you even async? (20)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Introduction to Apache Beam
Introduction to Apache BeamIntroduction to Apache Beam
Introduction to Apache Beam
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
aiohttp intro
aiohttp introaiohttp intro
aiohttp intro
 
A.java
A.javaA.java
A.java
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 
What is Socket Programming in Python | Edureka
What is Socket Programming in Python | EdurekaWhat is Socket Programming in Python | Edureka
What is Socket Programming in Python | Edureka
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
Windows 8 Apps and the Outside World
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
Alexey Orlenko ''High-performance IPC and RPC for microservices and apps''
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 

Mais de Saúl Ibarra Corretgé

Challenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicChallenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicSaúl Ibarra Corretgé
 
The Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetThe Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetSaúl Ibarra Corretgé
 
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveJitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveSaúl Ibarra Corretgé
 
Jitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedJitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedSaúl Ibarra Corretgé
 
Get a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceGet a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCSaúl Ibarra Corretgé
 
Jitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostJitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostSaúl Ibarra Corretgé
 
WebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTWebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTSaúl Ibarra Corretgé
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/oSaúl Ibarra Corretgé
 
Videoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCVideoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCSaúl Ibarra Corretgé
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSaúl Ibarra Corretgé
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasSaúl Ibarra Corretgé
 

Mais de Saúl Ibarra Corretgé (20)

Challenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemicChallenges running Jitsi Meet at scale during the pandemic
Challenges running Jitsi Meet at scale during the pandemic
 
The Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi MeetThe Road to End-to-End Encryption in Jitsi Meet
The Road to End-to-End Encryption in Jitsi Meet
 
Jitsi: State of the Union 2020
Jitsi: State of the Union 2020Jitsi: State of the Union 2020
Jitsi: State of the Union 2020
 
Jitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and loveJitsi Meet: our tale of blood, sweat, tears and love
Jitsi Meet: our tale of blood, sweat, tears and love
 
Jitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy mindedJitsi Meet: Video conferencing for the privacy minded
Jitsi Meet: Video conferencing for the privacy minded
 
Jitsi - Estado de la unión 2019
Jitsi - Estado de la unión 2019Jitsi - Estado de la unión 2019
Jitsi - Estado de la unión 2019
 
Get a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experienceGet a room! Spot: the ultimate physical meeting room experience
Get a room! Spot: the ultimate physical meeting room experience
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTC
 
Going Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTCGoing Mobile with React Native and WebRTC
Going Mobile with React Native and WebRTC
 
Jitsi: Estado de la Unión (2018)
Jitsi: Estado de la Unión (2018)Jitsi: Estado de la Unión (2018)
Jitsi: Estado de la Unión (2018)
 
Jitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-hostJitsi: state-of-the-art video conferencing you can self-host
Jitsi: state-of-the-art video conferencing you can self-host
 
WebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoTWebRTC: El epicentro de la videoconferencia y IoT
WebRTC: El epicentro de la videoconferencia y IoT
 
Jitsi: Open Source Video Conferencing
Jitsi: Open Source Video ConferencingJitsi: Open Source Video Conferencing
Jitsi: Open Source Video Conferencing
 
Jitsi: State of the Union
Jitsi: State of the UnionJitsi: State of the Union
Jitsi: State of the Union
 
libuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/olibuv: cross platform asynchronous i/o
libuv: cross platform asynchronous i/o
 
Videoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTCVideoconferencias: el santo grial de WebRTC
Videoconferencias: el santo grial de WebRTC
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application server
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincheras
 
A deep dive into libuv
A deep dive into libuvA deep dive into libuv
A deep dive into libuv
 
Planning libuv v2
Planning libuv v2Planning libuv v2
Planning libuv v2
 

Último

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Último (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Python, do you even async?

  • 1. Python, do you even async? Saúl Ibarra Corretgé @saghul DomCode, August 2014
  • 2. repr(self) >>> from Amsterdam import saghul >>> >>> saghul.work() VoIP, SIP, XMPP, chat, Real Time Communications >>> >>> saghul.other() networking, event loops, sockets, MOAR PYTHON >>> >>> saghul.languages() Python, C >>>
  • 4. Please give feedback! https://joind.in/event/view/2471
  • 5. The road to asynchronous i/o
  • 6. import socket import socket ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) print("Server listening on: {}".format(server.getsockname())) ! client, addr = server.accept() print("Client connected: {}".format(addr)) ! while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data) ! server.close()
  • 7. except Exception: • We can only handle one client at a time! • Solutions for handling multiple clients • Threads • I/O multiplexing • Check the C10K problem if you haven’t already! • http://www.kegel.com/c10k.html
  • 8. try: sockets + threads import socket import thread ! def handle_client(client, addr): print("Client connected: {}".format(addr)) while True: data = client.recv(4096) if not data: print("Client has disconnected") break client.send(data.upper()) ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) print("Server listening on: {}".format(server.getsockname())) ! while True: client, addr = server.accept() thread.start_new_thread(handle_client, (client, addr))
  • 9. except Exception: • Threads have overhead • Stack size • Context switching • Synchronisation • GIL? • Not for I/O!
  • 10. I/O multiplexing • Examine and block for I/O in multiple file descriptors at the same time • Single thread • A file descriptor is ready if the corresponding I/O operation can be performed without blocking • File descriptor has to be set to be non-blocking
  • 11. I/O is hard • Different paradigms in Unix vs Windows • “are you ready?” vs “call me later” • Frameworks • Abstract platform differences • Provide tools for easier development of applications
  • 12.
  • 13. The included batteries • select • asyncore / asyncchat • selectors • asyncio
  • 14. “batteries don’t fit” http://bit.ly/182HcHT
  • 15. Frameworks • Platform abstraction • Protocol implementations • Integration with other event loops: Qt, GLib, ... • Different API styles • Async file i/o?
  • 16. import twisted • Uses select, poll, kqueue, epoll from the select module • IOCP on Windows • Integration with other event loops • Factory / Protocol / Transport abstractions • Deferreds
  • 17. import tornado • Uses select, poll, kqueue, epoll from the select module • select() on Windows :-( • Mainly oriented to web development • Synchronous looking API with coroutines / Futures
  • 18. import gevent • Uses libev for platform abstraction • select() on Windows :-( • Syncronous API using greenlet • ME LIKEY! :-)
  • 20. I’m not trying to reinvent the wheel. I’m trying to build a good one. ! Guido van Rossum
  • 22. import asyncio • Reference implementation for PEP-3156 • Basic components for doing async i/o • Works on Python >= 3.3 • Trollius: backport for Python >= 2.6
  • 23. Goals • Modern implementation of asynchronous i/o for Python • Use yield from (PEP-380) • But don’t force it • Don’t use anything that requires Python > 3.3 • Interoperability with other frameworks
  • 24. Goals • Unix and Windows support • IPv4 and IPv6 • TCP, UDP and pipes • Basic SSL (secure by default) • Subprocesses
  • 25. Non goals • Perfection • Replacing current frameworks • Protocol implementations • Replace httplib, smtplib, ... • Make it work on Python < 3.3
  • 26. Interoperability twisted tornado gevent ... asyncio selectors iocp
  • 27. Example: Tornado tornado asyncio / twisted tornado epoll/kqueue
  • 29. Components Event loop, policy Coroutines, Futures, Tasks Transports, Protocols, Streams
  • 30. Calculate poll time Poll Run callbacks Event loop
  • 31. Event loop & policy • Chooses the best i/o mechanism for a given platform • APIs for creating server and client connections (TCP, UDP, …) • Establish the context for a loop
  • 32. Working with threads • loop.call_soon_threadsafe(func, *args) • loop.run_in_executor(exc, func, *args) • loop.set_default_executor(exc) ! • PEP-3148 executor
  • 34. Coroutines, Futures & Tasks • Coroutines • a generator function, can receive values • decorated with @coroutine • Future • promise of a result or an error • Task • Future which runs a coroutine
  • 35. Coroutines & yield from import asyncio import socket ! loop = asyncio.get_event_loop() ! @asyncio.coroutine def handle_client(client, addr): print("Client connected: {}".format(addr)) while True: data = yield from loop.sock_recv(client, 4096) if not data: print("Client has disconnected") break client.send(data) ! @asyncio.coroutine def accept_connections(server_socket): while True: client, addr = yield from loop.sock_accept(server_socket) asyncio.async(handle_client(client, addr)) ! server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(511) server.setblocking(False) print("Server listening on: {}".format(server.getsockname())) ! loop.run_until_complete(accept_connections(server))
  • 36. Coroutines & yield from • Imagine the yield from is not there • Imagine the code is executed sequentially • Not exactly the formal definition of yield from (from PEP-380)
  • 37. Futures • Similar to Futures from PEP-3148 • API (almost) identical • Adapted for asyncio’s single threaded model
  • 38. Futures + Coroutines • yield from works with Futures! • f = Future() • Someone will set the result or exception • r = yield from f • Waits until done and returns f.result() • Usually returned by functions
  • 39. Undoing callbacks (I) @asyncio.coroutine def sync_looking_function(*args): fut = asyncio.Future() def cb(result, error): if error is not None: fut.set_result(result) else: fut.set_exception(Exception(error)) async_function(cb, *args) return (yield from fut)
  • 40. Undoing callbacks (II) ! def sync_looking_function(*args): fut = asyncio.Future() def cb(result, error): if error is not None: fut.set_result(result) else: fut.set_exception(Exception(error)) async_function(cb, *args) return fut
  • 41. Tasks • Unicorns covered in fairy dust • It’s a coroutine wrapped in a Future • Inherits from Future • Works with yield from • r = yield from Task(coro(...))
  • 42. Tasks vs coroutines • A coroutine doesn’t “advance” without a scheduling mechanism • Tasks can advance in their own • The event loop is the scheduler!
  • 43. Example import asyncio ! loop = asyncio.get_event_loop() clients = {} # task -> (reader, writer) ! def accept_client(client_reader, client_writer): task = asyncio.Task(handle_client(client_reader, client_writer)) clients[task] = (client_reader, client_writer) ! def client_done(task): del clients[task] ! task.add_done_callback(client_done) ! @asyncio.coroutine def handle_client(client_reader, client_writer): while True: data = (yield from client_reader.readline()) client_writer.write(data) !! f = asyncio.start_server(accept_client, '127.0.0.1', 12345) server = loop.run_until_complete(f) loop.run_forever()
  • 45. Transports & Protocols • Transport: represents a connection (socket, pipe, ...) • Protocol: represents an application (HTTP server, IRC client, ...) • They always go together • API is based on function calls and callbacks
  • 46. Streams • Abstraction on top of transports / protocols • File-like API using coroutines
  • 47. Transport -> Protocol • connection_made(transport) • data_received(data) • eof_received() • connection_lost(exc) ! • UDP, pipes and subprocesses are slightly different
  • 48. Protocol -> Transport • write(data) • writelines(seq) • write_eof() • close()
  • 49. Enter Trollius! • Backport of asyncio for Python >= 2.6 • By Victor Stinner (@haypo) • Slightly different syntax • yield instead of yield from • raise Return(x) instead of return x on generators • pip install trollius
  • 50. That was all?! • Go read PEP-3156 • Implement a simple protocol (an IRC client for example) • Checkout the links on the last slide • Use asyncio in your next project
  • 52. Links • https://code.google.com/p/tulip/ • http://legacy.python.org/dev/peps/ pep-3156/ • https://code.google.com/p/tulip/wiki/ ThirdParty • http://asyncio.org/ • http://www.slideshare.net/saghul