SlideShare a Scribd company logo
@saghul
Introduction to asyncio
Saúl Ibarra Corretgé
PyLadies Amsterdam - 20th March 2014
github.com/saghul
Introduction to asyncio
Sockets 101
import socket
server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server.bind(('127.0.0.1', 1234))
server.listen(128)
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()
Scaling Up!
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(128)
print("Server listening on: {}".format(server.getsockname()))
while True:
client, addr = server.accept()
_thread.start_new_thread(handle_client, (client, addr))
Scaling Up! (really?)
Threads are too expensive
Also, context switching
Use an event loop instead!
The Async Way (TM)
Single thread
Block waiting for sockets to be ready to read or
write
Perform i/o operations and call the callbacks!
Repeat
(Windows is not like this)
Why asyncio?
asyncore and asynchat are not enough
Fresh new implementation of Asynchronous I/O
Python >= 3.3
Trollius: backport for Python >= 2.6
Use new language features: yield from
Designed to interoperate with other frameworks
Components
Event loop, policy
Coroutines, Futures, Tasks
Transports, Protocols
asyncio 101
import asyncio
loop = asyncio.get_event_loop()
@asyncio.coroutine
def infinity():
while True:
print("hello!")
yield from asyncio.sleep(1)
loop.run_until_complete(infinity())
Coroutines, futures &
tasks
Coroutines, futures & tasks
Coroutine
generator function, can receive values
decorated with @coroutine
Future
promise of a result or an error
Task
Future which runs a coroutine
Futures
Similar to Futures from PEP-3148
concurrent.futures.Future
API (almost) identical:
f.set_result(); r = f.result()
f.set_exception(e); e = f.exception()
f.done(); f.cancel(); f.cancelled()
f.add_done_callback(x); f.remove_done_callback(x)
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
@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)
Tasks
Unicorns covered in fairy dust
It’s a coroutine wrapped in a Future
WAT
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 on their own
The event loop is the scheduler!
Magic!
Echo Server
import asyncio
loop = asyncio.get_event_loop()
class EchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
print('Client connected')
self.transport = transport
def data_received(self, data):
print('Received data:',data)
self.transport.write(data)
def connection_lost(self, exc):
print('Connection closed', exc)
f = loop.create_server(lambda: EchoProtocol(), 'localhost', 1234)
server = loop.run_until_complete(f)
print('Server started')
loop.run_forever()
Echo Server Reloaded
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', 1234)
server = loop.run_until_complete(f)
loop.run_forever()
HTTP Server
import asyncio
import aiohttp
import aiohttp.server
class HttpServer(aiohttp.server.ServerHttpProtocol):
@asyncio.coroutine
def handle_request(self, message, payload):
print('method = {!r}; path = {!r}; version = {!r}'.format(
message.method, message.path, message.version))
response = aiohttp.Response(self.transport, 200, close=True)
response.add_header('Content-type', 'text/plain')
response.send_headers()
response.write(b'Hello world!rn')
response.write_eof()
loop = asyncio.get_event_loop()
f = loop.create_server(lambda: HttpServer(), 'localhost', 1234)
server = loop.run_until_complete(f)
loop.run_forever()
Redis
import asyncio
import asyncio_redis
@asyncio.coroutine
def subscriber(channels):
# Create connection
connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379)
# Create subscriber.
subscriber = yield from connection.start_subscribe()
# Subscribe to channel.
yield from subscriber.subscribe(channels)
# Wait for incoming events.
while True:
reply = yield from subscriber.next_published()
print('Received: ', repr(reply.value), 'on channel', reply.channel)
loop = asyncio.get_event_loop()
loop.run_until_complete(subscriber(['my-channel']))
More?
We just scratched the surface!
Read PEP-3156 (it’s an easy read, I promise!)
Checkout the documentation
Checkout the third-party libraries
Go implement something cool!
“I hear and I forget. I see and I remember.
I do and I understand.” - Confucius
Questions?
@saghul
bettercallsaghul.com

More Related Content

What's hot (20)

PDF
asyncio internals
Saúl Ibarra Corretgé
 
PDF
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
PDF
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
PDF
Vert.x clustering on Docker, CoreOS and ETCD
Tim Nolet
 
PDF
Python Coroutines, Present and Future
emptysquare
 
PPTX
All you need to know about the JavaScript event loop
Saša Tatar
 
PDF
PyCon lightning talk on my Toro module for Tornado
emptysquare
 
PDF
Event loop
codepitbull
 
PDF
Service Discovery for Continuous Delivery with Docker
Tim Nolet
 
PPTX
How NOT to write in Node.js
Piotr Pelczar
 
PDF
Tornado Web Server Internals
Praveen Gollakota
 
PPTX
Coroutines talk ppt
Shahroz Khan
 
PDF
.NET Multithreading and File I/O
Jussi Pohjolainen
 
PPTX
Bucks County Tech Meetup: node.js introduction
dshkolnikov
 
PPTX
Zeromq - Pycon India 2013
Srinivasan R
 
PDF
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
PDF
Of Owls and IO Objects
Felix Morgner
 
PPTX
Tornado web
kurtiss
 
PDF
Tornado in Depth
Òscar Vilaplana
 
asyncio internals
Saúl Ibarra Corretgé
 
Python meetup: coroutines, event loops, and non-blocking I/O
Buzzcapture
 
Metaprogramming and Reflection in Common Lisp
Damien Cassou
 
Vert.x clustering on Docker, CoreOS and ETCD
Tim Nolet
 
Python Coroutines, Present and Future
emptysquare
 
All you need to know about the JavaScript event loop
Saša Tatar
 
PyCon lightning talk on my Toro module for Tornado
emptysquare
 
Event loop
codepitbull
 
Service Discovery for Continuous Delivery with Docker
Tim Nolet
 
How NOT to write in Node.js
Piotr Pelczar
 
Tornado Web Server Internals
Praveen Gollakota
 
Coroutines talk ppt
Shahroz Khan
 
.NET Multithreading and File I/O
Jussi Pohjolainen
 
Bucks County Tech Meetup: node.js introduction
dshkolnikov
 
Zeromq - Pycon India 2013
Srinivasan R
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Víctor Bolinches
 
Of Owls and IO Objects
Felix Morgner
 
Tornado web
kurtiss
 
Tornado in Depth
Òscar Vilaplana
 

Viewers also liked (20)

PDF
PEP-3156: Async I/O en Python
Saúl Ibarra Corretgé
 
PDF
Seu primeiro loop com Python AsyncIO - TDC 2016
Carlos Maniero
 
PDF
asyncio community, one year later
Victor Stinner
 
PDF
Asyncio
Andrew Svetlov
 
PDF
Trust No One
Saúl Ibarra Corretgé
 
PDF
Planning libuv v2
Saúl Ibarra Corretgé
 
PDF
CDRTool: CDR mediation and rating engine for OpenSIPS
Saúl Ibarra Corretgé
 
PDF
Python, WebRTC and You (v2)
Saúl Ibarra Corretgé
 
PDF
The Future of the PBX
Saúl Ibarra Corretgé
 
PDF
Building an Open Source VoIP Hardware Phone
Saúl Ibarra Corretgé
 
PDF
libuv, NodeJS and everything in between
Saúl Ibarra Corretgé
 
PDF
WebRTC enabling your OpenSIPS infrastructure
Saúl Ibarra Corretgé
 
PDF
Tulip
Jose Galarza
 
PDF
From SIP to WebRTC and vice versa
Saúl Ibarra Corretgé
 
PDF
Proyecto Open Pi Phone
Saúl Ibarra Corretgé
 
PDF
A Curious Course on Coroutines and Concurrency
David Beazley (Dabeaz LLC)
 
PDF
SylkServer: State of the art RTC application server
Saúl Ibarra Corretgé
 
PDF
Escalabilidad horizontal desde las trincheras
Saúl Ibarra Corretgé
 
PDF
A deep dive into libuv
Saúl Ibarra Corretgé
 
PDF
libuv: cross platform asynchronous i/o
Saúl Ibarra Corretgé
 
PEP-3156: Async I/O en Python
Saúl Ibarra Corretgé
 
Seu primeiro loop com Python AsyncIO - TDC 2016
Carlos Maniero
 
asyncio community, one year later
Victor Stinner
 
Planning libuv v2
Saúl Ibarra Corretgé
 
CDRTool: CDR mediation and rating engine for OpenSIPS
Saúl Ibarra Corretgé
 
Python, WebRTC and You (v2)
Saúl Ibarra Corretgé
 
The Future of the PBX
Saúl Ibarra Corretgé
 
Building an Open Source VoIP Hardware Phone
Saúl Ibarra Corretgé
 
libuv, NodeJS and everything in between
Saúl Ibarra Corretgé
 
WebRTC enabling your OpenSIPS infrastructure
Saúl Ibarra Corretgé
 
From SIP to WebRTC and vice versa
Saúl Ibarra Corretgé
 
Proyecto Open Pi Phone
Saúl Ibarra Corretgé
 
A Curious Course on Coroutines and Concurrency
David Beazley (Dabeaz LLC)
 
SylkServer: State of the art RTC application server
Saúl Ibarra Corretgé
 
Escalabilidad horizontal desde las trincheras
Saúl Ibarra Corretgé
 
A deep dive into libuv
Saúl Ibarra Corretgé
 
libuv: cross platform asynchronous i/o
Saúl Ibarra Corretgé
 
Ad

Similar to Introduction to asyncio (20)

PPTX
Python queue solution with asyncio and kafka
Ondřej Veselý
 
PDF
Websockets talk at Rubyconf Uruguay 2010
Ismael Celis
 
PDF
Akka Futures and Akka Remoting
Knoldus Inc.
 
PDF
Arduino and the real time web
Andrew Fisher
 
PDF
Python concurrency: libraries overview
Andrii Mishkovskyi
 
PDF
Encrypt all transports
Eleanor McHugh
 
PDF
ZeroMQ: Messaging Made Simple
Ian Barber
 
PPTX
Socket.io v.0.8.3
Cleveroad
 
PPTX
Socket.io v.0.8.3
Maryna Vasina
 
PDF
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
PPT
Networking Core Concept
Rays Technologies
 
PPTX
session6-Network Programming.pptx
SrinivasanG52
 
PDF
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
PPT
Sockets intro
AviNash ChaVhan
 
PPTX
Tools for Making Machine Learning more Reactive
Jeff Smith
 
PDF
Lego: A brick system build by scala
lunfu zhong
 
PDF
MultiClient chatting berbasis gambar
yoyomay93
 
PPT
Network
phanleson
 
PDF
Actor Clustering with Docker Containers and Akka.Net in F#
Riccardo Terrell
 
PDF
async/await in Swift
Peter Friese
 
Python queue solution with asyncio and kafka
Ondřej Veselý
 
Websockets talk at Rubyconf Uruguay 2010
Ismael Celis
 
Akka Futures and Akka Remoting
Knoldus Inc.
 
Arduino and the real time web
Andrew Fisher
 
Python concurrency: libraries overview
Andrii Mishkovskyi
 
Encrypt all transports
Eleanor McHugh
 
ZeroMQ: Messaging Made Simple
Ian Barber
 
Socket.io v.0.8.3
Cleveroad
 
Socket.io v.0.8.3
Maryna Vasina
 
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
Networking Core Concept
Rays Technologies
 
session6-Network Programming.pptx
SrinivasanG52
 
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Sockets intro
AviNash ChaVhan
 
Tools for Making Machine Learning more Reactive
Jeff Smith
 
Lego: A brick system build by scala
lunfu zhong
 
MultiClient chatting berbasis gambar
yoyomay93
 
Network
phanleson
 
Actor Clustering with Docker Containers and Akka.Net in F#
Riccardo Terrell
 
async/await in Swift
Peter Friese
 
Ad

More from Saúl Ibarra Corretgé (19)

PDF
JanusCon 2024: Mom there are robots in my meeting
Saúl Ibarra Corretgé
 
PDF
Challenges running Jitsi Meet at scale during the pandemic
Saúl Ibarra Corretgé
 
PDF
The Road to End-to-End Encryption in Jitsi Meet
Saúl Ibarra Corretgé
 
PDF
Jitsi: State of the Union 2020
Saúl Ibarra Corretgé
 
PDF
Jitsi Meet: our tale of blood, sweat, tears and love
Saúl Ibarra Corretgé
 
PDF
Jitsi Meet: Video conferencing for the privacy minded
Saúl Ibarra Corretgé
 
PDF
Jitsi - Estado de la unión 2019
Saúl Ibarra Corretgé
 
PDF
Get a room! Spot: the ultimate physical meeting room experience
Saúl Ibarra Corretgé
 
PDF
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
PDF
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
PDF
Jitsi: Estado de la Unión (2018)
Saúl Ibarra Corretgé
 
PDF
Jitsi: state-of-the-art video conferencing you can self-host
Saúl Ibarra Corretgé
 
PDF
WebRTC: El epicentro de la videoconferencia y IoT
Saúl Ibarra Corretgé
 
PDF
Jitsi: Open Source Video Conferencing
Saúl Ibarra Corretgé
 
PDF
Jitsi: State of the Union
Saúl Ibarra Corretgé
 
PDF
Videoconferencias: el santo grial de WebRTC
Saúl Ibarra Corretgé
 
PDF
Extendiendo SIP con WebRTC
Saúl Ibarra Corretgé
 
PDF
De SIP a WebRTC y vice versa
Saúl Ibarra Corretgé
 
PDF
Python, WebRTC and You
Saúl Ibarra Corretgé
 
JanusCon 2024: Mom there are robots in my meeting
Saúl Ibarra Corretgé
 
Challenges running Jitsi Meet at scale during the pandemic
Saúl Ibarra Corretgé
 
The Road to End-to-End Encryption in Jitsi Meet
Saúl Ibarra Corretgé
 
Jitsi: State of the Union 2020
Saúl Ibarra Corretgé
 
Jitsi Meet: our tale of blood, sweat, tears and love
Saúl Ibarra Corretgé
 
Jitsi Meet: Video conferencing for the privacy minded
Saúl Ibarra Corretgé
 
Jitsi - Estado de la unión 2019
Saúl Ibarra Corretgé
 
Get a room! Spot: the ultimate physical meeting room experience
Saúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
Going Mobile with React Native and WebRTC
Saúl Ibarra Corretgé
 
Jitsi: Estado de la Unión (2018)
Saúl Ibarra Corretgé
 
Jitsi: state-of-the-art video conferencing you can self-host
Saúl Ibarra Corretgé
 
WebRTC: El epicentro de la videoconferencia y IoT
Saúl Ibarra Corretgé
 
Jitsi: Open Source Video Conferencing
Saúl Ibarra Corretgé
 
Jitsi: State of the Union
Saúl Ibarra Corretgé
 
Videoconferencias: el santo grial de WebRTC
Saúl Ibarra Corretgé
 
Extendiendo SIP con WebRTC
Saúl Ibarra Corretgé
 
De SIP a WebRTC y vice versa
Saúl Ibarra Corretgé
 
Python, WebRTC and You
Saúl Ibarra Corretgé
 

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 

Introduction to asyncio

  • 1. @saghul Introduction to asyncio Saúl Ibarra Corretgé PyLadies Amsterdam - 20th March 2014
  • 4. Sockets 101 import socket server = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) server.bind(('127.0.0.1', 1234)) server.listen(128) 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()
  • 5. Scaling Up! 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(128) print("Server listening on: {}".format(server.getsockname())) while True: client, addr = server.accept() _thread.start_new_thread(handle_client, (client, addr))
  • 6. Scaling Up! (really?) Threads are too expensive Also, context switching Use an event loop instead!
  • 7. The Async Way (TM) Single thread Block waiting for sockets to be ready to read or write Perform i/o operations and call the callbacks! Repeat (Windows is not like this)
  • 8. Why asyncio? asyncore and asynchat are not enough Fresh new implementation of Asynchronous I/O Python >= 3.3 Trollius: backport for Python >= 2.6 Use new language features: yield from Designed to interoperate with other frameworks
  • 9. Components Event loop, policy Coroutines, Futures, Tasks Transports, Protocols
  • 10. asyncio 101 import asyncio loop = asyncio.get_event_loop() @asyncio.coroutine def infinity(): while True: print("hello!") yield from asyncio.sleep(1) loop.run_until_complete(infinity())
  • 12. Coroutines, futures & tasks Coroutine generator function, can receive values decorated with @coroutine Future promise of a result or an error Task Future which runs a coroutine
  • 13. Futures Similar to Futures from PEP-3148 concurrent.futures.Future API (almost) identical: f.set_result(); r = f.result() f.set_exception(e); e = f.exception() f.done(); f.cancel(); f.cancelled() f.add_done_callback(x); f.remove_done_callback(x)
  • 14. 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
  • 15. Undoing callbacks @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)
  • 16. Tasks Unicorns covered in fairy dust It’s a coroutine wrapped in a Future WAT Inherits from Future Works with yield from! r = yield from Task(coro(...))
  • 17. Tasks vs coroutines A coroutine doesn’t “advance” without a scheduling mechanism Tasks can advance on their own The event loop is the scheduler! Magic!
  • 18. Echo Server import asyncio loop = asyncio.get_event_loop() class EchoProtocol(asyncio.Protocol): def connection_made(self, transport): print('Client connected') self.transport = transport def data_received(self, data): print('Received data:',data) self.transport.write(data) def connection_lost(self, exc): print('Connection closed', exc) f = loop.create_server(lambda: EchoProtocol(), 'localhost', 1234) server = loop.run_until_complete(f) print('Server started') loop.run_forever()
  • 19. Echo Server Reloaded 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', 1234) server = loop.run_until_complete(f) loop.run_forever()
  • 20. HTTP Server import asyncio import aiohttp import aiohttp.server class HttpServer(aiohttp.server.ServerHttpProtocol): @asyncio.coroutine def handle_request(self, message, payload): print('method = {!r}; path = {!r}; version = {!r}'.format( message.method, message.path, message.version)) response = aiohttp.Response(self.transport, 200, close=True) response.add_header('Content-type', 'text/plain') response.send_headers() response.write(b'Hello world!rn') response.write_eof() loop = asyncio.get_event_loop() f = loop.create_server(lambda: HttpServer(), 'localhost', 1234) server = loop.run_until_complete(f) loop.run_forever()
  • 21. Redis import asyncio import asyncio_redis @asyncio.coroutine def subscriber(channels): # Create connection connection = yield from asyncio_redis.Connection.create(host='localhost', port=6379) # Create subscriber. subscriber = yield from connection.start_subscribe() # Subscribe to channel. yield from subscriber.subscribe(channels) # Wait for incoming events. while True: reply = yield from subscriber.next_published() print('Received: ', repr(reply.value), 'on channel', reply.channel) loop = asyncio.get_event_loop() loop.run_until_complete(subscriber(['my-channel']))
  • 22. More? We just scratched the surface! Read PEP-3156 (it’s an easy read, I promise!) Checkout the documentation Checkout the third-party libraries Go implement something cool! “I hear and I forget. I see and I remember. I do and I understand.” - Confucius