SlideShare a Scribd company logo
Asynchronous Python with Twisted
Who Am I?
Developer/Evangelist at LaunchKey
Organizer of Las Vegas Python User Group
Founder/Co-Organizer of Las Vegas PHP UG
Co-Organizer of Las Vegas Developer UG
National Junior Basketball Coach
What is Asynchronous
Programming?
• Non-Linear
• Event Driven
• Functional
• Depends on non-blocking code
Why Asynchronous?
One thread for all connections with the following
benefits:
Shared application level objects and data reduces
memory footprint per connection
Limited threads allows for better CPU utilization of each
core thus fewer cores overall.
Both of the above enable large applications to run on
smaller virtual machines in the cloud.
What’s the Catch?
Functional non-blocking code development has a
learning curve.
Developing applications with objects that persist
beyond a single request can be more difficult than
standard WSGI applications.
Requires asynchronous libraries which can be
scarce in Python.
Twisted
Established Asynchronous Python Framework
1.0 Release was in March 2004
Utilizes asynchronous I/O
Server runs in Python 2.6+ and 3.2+
Deferred = Asynchronous
Analogous to promises/futures
Returned by asynchronous and concurrent calls
Use callbacks to process result of fulfillment
Process callbacks in the order they are registered with
each being passed the result of the predecessor
Can be quickly created for static data with defer.sucess
and defer.failure functions
Callback Example
d = defer.Deferred()
d.addCallback(lambda x: x + “ is an “)
d.addCallback(lambda x: x + “ example!“)
d.callback(“This”)
>>> This is an example!
Deferred Error Handling
Deferred objects catch all callback Exceptions
Exceptions are wrapped in a Failure object which can
also be returned by a callback or errback
If no errbacks remain, exception is swallowed and
processing is stopped
Remaining callbacks before next errback are skipped
If errback returns non-Failure, callback processing
resumes
Callback Non-Failure Flow
Deferred callback(result)
• callback - success
• callback – success
• errback - skipped
• errback – skipped
Errback Non-Failure Flow
Deferred callback(result)
• callback - success
• errback - failure
• callback – success
• errback – skipped
Errback Failure Flow
Deferred callback(result)
• callback - success
• callback – failure
• errback - failure
• errback – success
Threads = Concurrent
Threads run in thread pool managed by reactor
callInThread executes function in its own thread with
supplied data
deferToThread works like callInThread but returns a
Deferred object and processes the callbacks when
complete
Use threads for blocking code
Reactor
Manages the main event loop
Waits for and dispatches events or messages
May have predefined services to provide access to
network communications, threading, and event
dispatching. Available services are operating system
dependent
Application Hierarchy
Protocols
Service
Application Mail
SSL
Web
Mail
SMTP
UDP
StatsD
Application
Starts and stops the reactor
Manages services
Handles logging
Can run as daemon
Service
Registers with the reactor
Processed in the main event loop
Manages connections
Communicates via Protocols
Predefined Services
File Descriptor
Process
Threads
Time (scheduling)
SSL
TCP
UDP
UNIX (UNIX sockets)
Socket (3rd Party
Sockets)
Protocol
Utilized for interaction with services
Services with stateful connections utilize protocol
factories to generate a protocol instance per
connection.
Provided with method to send data to connection in
the form of transports or producers
Protocol Factory
Builds protocol instances
Injected into every protocol instance
Meant to perform inter-instance interaction
Can be used as testable registry for registry pattern
implementations
Included Protocols
AMP
Basic
Dict
Finger
FTP
GPS
HTB
HTTP
Ident
Loopback
Memcache
Mice
PCP
Portforward
Postfix
Shoutcast
SIP
SOCKSv4
Stateful
Telnet
TLS
Wire
Available Protocols
Mongo
LDAP
Dict
Finger
FTP
GPS
HTB
HTTP
Ident
Loopback
Memcache
Mice
PCP
Portforward
Postfix
Shoutcast
SIP
SOCKSv4
Stateful
Telnet
TLS
Wire
MongoDB*
LDAP*
* External packages maintained by Twisted Matrix Labs
Twisted Web
Web server built on Twisted HTTP Protocol
Can be stand alone web server
Can embedded as part of an application
Supports all of the features of most modern web
servers
Web Server Features
Virtual hosts
Proxy/Reverse proxy
Scripts (hello.py)
Static files
CGI
WSGI
URL rewrites
MIME processors
Sessions
Simple Web Application
Site object is root Resource
Resource object represents URL segment
Tree hierarchy of resources
Can directly return string or write response via
request object for deferred processing
Example Hierarchy
/
foo/
bar/
bat/
fizz/buz
Example Hierarchy Code
root = RootResource()
foo = FooResource()
foo.putChild(“bar”, BarResource())
foo.putChild(“bat”, BatResource())
root.putChild(“foo”, foo)
root.putChild(“fiz/buzz”, FizBuzzResource())
reactor.listenTCP(8080, Site(root))
reactor.start()
Concurrent Example
from twisted.web import resource
class DemoResource(resource.Resource):
def render_GET(self, request):
return "<html>foo</html>"
Deferred Example
def render_GET(self, request):
def process_resp(html, request):
request.write(html)
request.finish()
deferred = self.async_client.request()
deferred.addCallback(process_resp, request)
return NOT_DONE_YET
Demo Time
Example on GitHub:
https://github.com/aenglander/demo-python-twisted-
websocket
@adam_englander
#launchkey on freenode.net
#vegastech on freenode.net
adam@launchkey.com

More Related Content

What's hot (20)

PDF
Docker and Maestro for fun, development and profit
Maxime Petazzoni
 
PPTX
Evented Ruby VS Node.js
Nitin Gupta
 
PDF
Microservices with Micronaut
QAware GmbH
 
PDF
iptables and Kubernetes
HungWei Chiu
 
ODP
Developing high-performance network servers in Lisp
Vladimir Sedach
 
PDF
Observability beyond logging for Java Microservices
Luke Marsden
 
PDF
IP Virtual Server(IPVS) 101
HungWei Chiu
 
PDF
[En] IPVS for Docker Containers
Andrey Sibirev
 
PDF
Mininet: Moving Forward
ON.Lab
 
PPTX
Notes on Netty baics
Rick Hightower
 
PPTX
How fluentd fits into the modern software landscape
Phil Wilkins
 
PDF
How Networking works with Data Science
HungWei Chiu
 
PDF
How to install and use Kubernetes
Luke Marsden
 
PDF
Control Your Network ASICs, What Benefits switchdev Can Bring Us
HungWei Chiu
 
KEY
Distributed app development with nodejs and zeromq
Ruben Tan
 
PDF
Ractor's speed is not light-speed
SATOSHI TAGOMORI
 
PDF
Docker and Fluentd
SATOSHI TAGOMORI
 
PDF
Head First to Container&Kubernetes
HungWei Chiu
 
PPT
Reactive programming with examples
Peter Lawrey
 
PDF
Docker Meetup: Docker Networking 1.11, by Madhu Venugopal
Michelle Antebi
 
Docker and Maestro for fun, development and profit
Maxime Petazzoni
 
Evented Ruby VS Node.js
Nitin Gupta
 
Microservices with Micronaut
QAware GmbH
 
iptables and Kubernetes
HungWei Chiu
 
Developing high-performance network servers in Lisp
Vladimir Sedach
 
Observability beyond logging for Java Microservices
Luke Marsden
 
IP Virtual Server(IPVS) 101
HungWei Chiu
 
[En] IPVS for Docker Containers
Andrey Sibirev
 
Mininet: Moving Forward
ON.Lab
 
Notes on Netty baics
Rick Hightower
 
How fluentd fits into the modern software landscape
Phil Wilkins
 
How Networking works with Data Science
HungWei Chiu
 
How to install and use Kubernetes
Luke Marsden
 
Control Your Network ASICs, What Benefits switchdev Can Bring Us
HungWei Chiu
 
Distributed app development with nodejs and zeromq
Ruben Tan
 
Ractor's speed is not light-speed
SATOSHI TAGOMORI
 
Docker and Fluentd
SATOSHI TAGOMORI
 
Head First to Container&Kubernetes
HungWei Chiu
 
Reactive programming with examples
Peter Lawrey
 
Docker Meetup: Docker Networking 1.11, by Madhu Venugopal
Michelle Antebi
 

Viewers also liked (20)

PDF
Python twisted
Mahendra M
 
PDF
Обзор фреймворка Twisted
Python Meetup
 
PDF
Async Python
Victoria Fantasy
 
ODP
Kyua and Jenkins: Testing Framework for BSD
Craig Rodrigues
 
PDF
Introduction to Python and Web Programming
David Neiss
 
PDF
Snakes on the Web
Jacob Kaplan-Moss
 
PDF
Python and the Web
pycontw
 
PDF
Building an inflight entertainment system controller in twisted
David Novakovic
 
ODP
Why Python Web Frameworks Are Changing the Web
joelburton
 
PPT
OSCon - Performance vs Scalability
Gleicon Moraes
 
PDF
Спецификация WSGI (PEP-333)
lectureswww lectureswww
 
PDF
Зоопарк python веб-фреймворков
PyNSK
 
PPTX
Python talk web frameworks
Kat Chuang
 
PDF
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp
 
PDF
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp
 
PPTX
Чем Python плох для стартапа?
PyNSK
 
PDF
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
WebCamp
 
PDF
Framework Battle: Django vs Flask vs Chalice
STEP Computer Academy (Zaporozhye)
 
KEY
LvivPy - Flask in details
Max Klymyshyn
 
PDF
Async Web Frameworks in Python
Ryan Johnson
 
Python twisted
Mahendra M
 
Обзор фреймворка Twisted
Python Meetup
 
Async Python
Victoria Fantasy
 
Kyua and Jenkins: Testing Framework for BSD
Craig Rodrigues
 
Introduction to Python and Web Programming
David Neiss
 
Snakes on the Web
Jacob Kaplan-Moss
 
Python and the Web
pycontw
 
Building an inflight entertainment system controller in twisted
David Novakovic
 
Why Python Web Frameworks Are Changing the Web
joelburton
 
OSCon - Performance vs Scalability
Gleicon Moraes
 
Спецификация WSGI (PEP-333)
lectureswww lectureswww
 
Зоопарк python веб-фреймворков
PyNSK
 
Python talk web frameworks
Kat Chuang
 
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp
 
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp
 
Чем Python плох для стартапа?
PyNSK
 
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
WebCamp
 
Framework Battle: Django vs Flask vs Chalice
STEP Computer Academy (Zaporozhye)
 
LvivPy - Flask in details
Max Klymyshyn
 
Async Web Frameworks in Python
Ryan Johnson
 
Ad

Similar to Asynchronous Python with Twisted (20)

PPTX
Async programming and python
Chetan Giridhar
 
PDF
Building Web APIs that Scale
Salesforce Developers
 
PDF
Twisted
Michal Sedlak
 
PDF
Python, do you even async?
Saúl Ibarra Corretgé
 
PDF
The art of concurrent programming
Iskren Chernev
 
PPTX
Using Coroutines to Create Efficient, High-Concurrency Web Applications
Matt Spitz
 
PDF
Concurrency, Parallelism And IO
Piyush Katariya
 
PPTX
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
PDF
Introduction to asyncio
Saúl Ibarra Corretgé
 
PDF
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
Peerbits
 
PDF
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
PDF
Concurrecny inf sharp
Riccardo Terrell
 
PPTX
Asynchronous programming - .NET Way
Bishnu Rawal
 
PDF
Tornado in Depth
Òscar Vilaplana
 
PDF
Asynchronous I/O in Python 3
Feihong Hsu
 
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
PDF
Asynchronous Programming. Talk from ESUG2024
ESUG
 
PDF
A first look into the Project Loom in Java
Lukas Steinbrecher
 
PDF
Awesome Concurrency with Elixir Tasks
Jonathan Magen
 
Async programming and python
Chetan Giridhar
 
Building Web APIs that Scale
Salesforce Developers
 
Twisted
Michal Sedlak
 
Python, do you even async?
Saúl Ibarra Corretgé
 
The art of concurrent programming
Iskren Chernev
 
Using Coroutines to Create Efficient, High-Concurrency Web Applications
Matt Spitz
 
Concurrency, Parallelism And IO
Piyush Katariya
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
Introduction to asyncio
Saúl Ibarra Corretgé
 
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
Peerbits
 
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
Concurrecny inf sharp
Riccardo Terrell
 
Asynchronous programming - .NET Way
Bishnu Rawal
 
Tornado in Depth
Òscar Vilaplana
 
Asynchronous I/O in Python 3
Feihong Hsu
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
Asynchronous Programming. Talk from ESUG2024
ESUG
 
A first look into the Project Loom in Java
Lukas Steinbrecher
 
Awesome Concurrency with Elixir Tasks
Jonathan Magen
 
Ad

More from Adam Englander (20)

PPTX
Making PHP Smarter - Dutch PHP 2023.pptx
Adam Englander
 
PDF
Practical API Security - PyCon 2019
Adam Englander
 
PDF
Threat Modeling for Dummies
Adam Englander
 
PDF
ZendCon 2018 - Practical API Security
Adam Englander
 
PDF
ZendCon 2018 - Cryptography in Depth
Adam Englander
 
PDF
Threat Modeling for Dummies - Cascadia PHP 2018
Adam Englander
 
PDF
Dutch PHP 2018 - Cryptography for Beginners
Adam Englander
 
PDF
php[tek] 2108 - Cryptography Advances in PHP 7.2
Adam Englander
 
PDF
php[tek] 2018 - Biometrics, fantastic failure point of the future
Adam Englander
 
PDF
Biometrics: Sexy, Secure and... Stupid - RSAC 2018
Adam Englander
 
PPTX
Practical API Security - PyCon 2018
Adam Englander
 
PDF
Practical API Security - Midwest PHP 2018
Adam Englander
 
PDF
Cryptography for Beginners - Midwest PHP 2018
Adam Englander
 
PDF
Cryptography for Beginners - Sunshine PHP 2018
Adam Englander
 
PDF
ConFoo Vancouver 2017 - Biometrics: Fantastic Failure Point of the Future
Adam Englander
 
PDF
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
Adam Englander
 
PDF
ZendCon 2017 - Cryptography for Beginners
Adam Englander
 
PDF
ZendCon 2017: The Red Team is Coming
Adam Englander
 
PDF
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
PDF
Symfony Live San Franciso 2017 - BDD API Development with Symfony and Behat
Adam Englander
 
Making PHP Smarter - Dutch PHP 2023.pptx
Adam Englander
 
Practical API Security - PyCon 2019
Adam Englander
 
Threat Modeling for Dummies
Adam Englander
 
ZendCon 2018 - Practical API Security
Adam Englander
 
ZendCon 2018 - Cryptography in Depth
Adam Englander
 
Threat Modeling for Dummies - Cascadia PHP 2018
Adam Englander
 
Dutch PHP 2018 - Cryptography for Beginners
Adam Englander
 
php[tek] 2108 - Cryptography Advances in PHP 7.2
Adam Englander
 
php[tek] 2018 - Biometrics, fantastic failure point of the future
Adam Englander
 
Biometrics: Sexy, Secure and... Stupid - RSAC 2018
Adam Englander
 
Practical API Security - PyCon 2018
Adam Englander
 
Practical API Security - Midwest PHP 2018
Adam Englander
 
Cryptography for Beginners - Midwest PHP 2018
Adam Englander
 
Cryptography for Beginners - Sunshine PHP 2018
Adam Englander
 
ConFoo Vancouver 2017 - Biometrics: Fantastic Failure Point of the Future
Adam Englander
 
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
Adam Englander
 
ZendCon 2017 - Cryptography for Beginners
Adam Englander
 
ZendCon 2017: The Red Team is Coming
Adam Englander
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
Adam Englander
 
Symfony Live San Franciso 2017 - BDD API Development with Symfony and Behat
Adam Englander
 

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 

Asynchronous Python with Twisted