SlideShare a Scribd company logo
1 of 40
Download to read offline
WTF is Twisted?
(or: Owl Amongst The Ponies)
About HawkOwl
• hawkowl@atleastfornow.net
• @hawkieowl on Twitter
• hawkowl on GitHub, Keybase &
ThoughtStreams
• PGP Key Fingerprint:

2100 5027 897E C8AE 1D94

A905 2308 B479 D392 4A11
• Twisted Core Committer and Release
Manager (13.2 & 14.0)
• Is not actually an owl
Twisted in One Slide
• Twisted is a framework for writing network
applications in Python
• Best known for “Deferreds”, Twisted’s async
abstraction
• Contains protocol implementations for HTTP,
SMTP, IMAP, DNS, etc.
Why would you want to use
Twisted?
• Higher performance in some common situations
• Stable, mature codebase
• Protocol implementations for lots of things
• High test coverage
• Great community consisting of excellent
individuals who do excellent work
What makes Twisted especially
different from other projects?
• Twisted has a reputation for being the “black
sheep” in the Python community, mostly
because we do things “weirdly” and “hard”
• But, surprise! It turns out the Twisted developers
were right all along (see: asyncio)
• Different set of principals, from both the
longevity of the project and their specific
problems
The Tenets of Twisted
(the time-tested, battle-hardened principals of the
Twisted project, as interpreted by HawkOwl)
Subclassing is bad.
Composition is the new inheritance!
Multiple inheritance is
really bad.
Handy hint: If you’ve written the word “super”, it’s
already too late.
Time-based releases
are king.
For large, evolving frameworks, it’s better to gradually
change than have a massive app migration effort.
Early APIs > No APIS
You won’t know how your API works in the real world until
other people use it. You can always deprecate it later.
All code needs tests.
No exceptions.
It doesn’t matter if you’re fixing an urgent release regression
- an eye on coverage saves you a lot of time later.
All code needs reviewing.
No exceptions.
Code review is invaluable, even if it does descend into
bikeshedding if they can’t find anything wrong.
Only bad APIs can’t
be unit tested.
Can’t unit test your API? Too bad, time to refactor it.
Build slaves are
amazing.
Test your code on everything. Virtual machines are
cheap, compatibility problems down the line are not.
–David Reid, Glyph, et al
“Call a function with some arguments and
inspect some return values.”
How Twisted Works
(a short, mostly-correct overview)
The Event Loop
(Spin me right round, baby, right round)
The Reactor
• Twisted, being an event-driven framework,
provides an event loop, or “reactor”.
• This is an infinite loop, wrapped around a blocking
call that waits until some I/O is ready
• Once the I/O is ready, this fires off an event to run
the code that was waiting for it
• Runs other tasks while I/O blocked tasks are
waiting
Using the Reactor
• To utilise the reactor, you use Deferreds.
• Deferreds are an “IOU” for an actual result
sometime in the future
• A Deferred contains a callback chain, a series of
functions run in sequence after it gets a result
• Deferreds get their results from events occurring -
such as I/O being received or some task being
finished
Benefits
• For I/O bound applications, allows you to
efficiently use CPU resources, as the reactor
runs other things in the meantime
• Integration with common event loops - for
example, GTK or QT, to use your Twisted code
into your GTK or QT applications
The Callback Chain
(Hey, I just met you, and this is crazy,

but here’s a function, so call it maybe?)
The Callback Chain
• The easiest way to understand the callback
chain is to visualise it as a production line.
• A production line is made up of discrete blocks -
each doing a separate thing.
• Let’s imagine a such a production line…
Lets say that we are building a toy car, and we
need to do the following:
1. Create toy car body from materials
2. Paint racing stripes on car body
3. Add wheels to the car body
4. Put the completed car in a box
Here is how we would do that in psuedo-code
Deferreds:
!
! d = Deferred()!
!d.addCallback(buildCarBody)!
d.addCallback(paintStripes)!
d.addCallback(addWheels)!
d.addCallback(placeInBox)!
# Start the callback chain!
d.callback(rawMaterials)
Deferreds
• Each function in the chain is called with the
result of the previous one as its first argument
• Functions in the callback chain can return either
a result or a Deferred that fires with a result
sometime in the future
Lists of Deferreds
• If you have several Deferred operations to do at
the same time, and want your callback to fire
only when they are all done, use
DeferredList.!
• Pass it a list of Deferreds, and it will return a
Deferred that fires with a list containing the
results of each when they have all finished.
Error Handling
• Error handling is done by errbacks.
• Errbacks are like callbacks, but are run when an
exception is raised.
• An errback will catch all errors that occur on the
chain before it.
Deferred Benefits
• Forces you to break up your logic into sections,
broken up over external interface accesses
• Encourages reuse, as these sections quite
commonly do one thing to an input and return it
• Can be cancelled (eg. if a client disconnected
and you don’t care about the result anymore)
Deferred Benefits
• Discourages global mutable state by having
different execution threads share the same
global state
• No global mutable state means you can scale
easier
• If your global state is databases, just spin up
more Twisted instances to use all your CPUs
Extending the Callback Chain
(Because sometimes things like to do other things)
Deferreds returning
Deferreds
• Deferreds can contain their own callback chain -
meaning that one Deferred returned may have
several callbacks being called inside it
• This is invisible to the “top level” of callbacks
• You can extend your callback chain at any time
What can Twisted do?
(Enough of the boring stuff!)
Web
• Klein, a Flask-like API in Twisted
• Saratoga, a HTTP API framework
• Autobahn, a Websockets implementation
• Hendrix, a Django deployment framework
• Static file serving: 

twistd -n web --port tcp:8080 --path /tmp
Klein (Flask in Twisted)
from klein import Klein!
app = Klein()!
!
@app.route('/')!
def home(request):!
return 'Hello, world!'!
!
app.run("localhost", 8080)
Saratoga (HTTP API)
{!
"metadata": {!
"name": “APIExample", "versions": [1]!
},!
"endpoints": [{!
! ! "endpoint": “example", "getProcessors": [!
{"versions": [1]}!
]}!
]}!
from saratoga.api import SaratogaAPI!
import json!
!
class APIExample(object):!
class v1(object):!
def example_GET(self, request, params):!
return {"hello": "world"}!
!
api = SaratogaAPI(APIExample, json.load(open("apidef.json")))!
api.run()
Email
• Complete SMTP and ESMTP server and clients
• POP3 and IMAP4 servers and clients
• Support for TLS-secured email out of the box



For more info, see:

http://twistedmatrix.com/documents/
current/mail/index.html
DNS
• A caching, recursive DNS server out of the box

twistd -n dns -c —port 10053 --recursive
• DNS client APIs
• DNS server toolkit



For more info, see:

http://twistedmatrix.com/documents/
current/names/howto/custom-server.html
Chat
• IRC Server

twistd -n words --irc-port tcp:8400
--group roomname --auth memory:usr:pass
• IRC client (for making IRC bots)
• XMPP client



For more info, see: 

http://twistedmatrix.com/documents/
current/words/examples/
Want to know more?
• Twisted Docs

http://twistedmatrix.com/documents/current/
• Iffy’s Twisted FTW

http://iffycan.com/twistedftw/
• HawkOwl’s Technicals

http://technicals.atleastfornow.net/
Questions?
(sane answers not guaranteed)

More Related Content

What's hot

Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System DevelopmentAllan Huang
 
Securing & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetSecuring & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetLuke Marsden
 
iptables and Kubernetes
iptables and Kubernetesiptables and Kubernetes
iptables and KubernetesHungWei Chiu
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in LispDeveloping high-performance network servers in Lisp
Developing high-performance network servers in LispVladimir Sedach
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.jsNitin Gupta
 
Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Jaap ter Woerds
 
IP Virtual Server(IPVS) 101
IP Virtual Server(IPVS) 101IP Virtual Server(IPVS) 101
IP Virtual Server(IPVS) 101HungWei Chiu
 
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)Kubernetes @ Squarespace (SRE Portland Meetup October 2017)
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)Kevin Lynch
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with MicronautQAware GmbH
 
[En] IPVS for Docker Containers
[En] IPVS for Docker Containers[En] IPVS for Docker Containers
[En] IPVS for Docker ContainersAndrey Sibirev
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016Susan Potter
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole
[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole
[네이버오픈소스세미나] What’s new in Zipkin - Adrian ColeNAVER Engineering
 
Mininet: Moving Forward
Mininet: Moving ForwardMininet: Moving Forward
Mininet: Moving ForwardON.Lab
 
Head First to Container&Kubernetes
Head First to Container&KubernetesHead First to Container&Kubernetes
Head First to Container&KubernetesHungWei Chiu
 
iptables 101- bottom-up
iptables 101- bottom-upiptables 101- bottom-up
iptables 101- bottom-upHungWei Chiu
 

What's hot (20)

Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
 
Securing & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetSecuring & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave Net
 
iptables and Kubernetes
iptables and Kubernetesiptables and Kubernetes
iptables and Kubernetes
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in LispDeveloping high-performance network servers in Lisp
Developing high-performance network servers in Lisp
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.js
 
Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...
 
IP Virtual Server(IPVS) 101
IP Virtual Server(IPVS) 101IP Virtual Server(IPVS) 101
IP Virtual Server(IPVS) 101
 
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)Kubernetes @ Squarespace (SRE Portland Meetup October 2017)
Kubernetes @ Squarespace (SRE Portland Meetup October 2017)
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Building Netty Servers
Building Netty ServersBuilding Netty Servers
Building Netty Servers
 
[En] IPVS for Docker Containers
[En] IPVS for Docker Containers[En] IPVS for Docker Containers
[En] IPVS for Docker Containers
 
Docker and Fluentd
Docker and FluentdDocker and Fluentd
Docker and Fluentd
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole
[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole
[네이버오픈소스세미나] What’s new in Zipkin - Adrian Cole
 
Mininet: Moving Forward
Mininet: Moving ForwardMininet: Moving Forward
Mininet: Moving Forward
 
Head First to Container&Kubernetes
Head First to Container&KubernetesHead First to Container&Kubernetes
Head First to Container&Kubernetes
 
iptables 101- bottom-up
iptables 101- bottom-upiptables 101- bottom-up
iptables 101- bottom-up
 
Event machine
Event machineEvent machine
Event machine
 

Viewers also liked

Building an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twistedBuilding an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twistedDavid Novakovic
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityGleicon Moraes
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedPython Meetup
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en Twitter
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en TwitterLas 5 preocupaciones en Twitter sobre la salida de Claudio Palma en Twitter
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en TwitterRoberto Guerra
 
SBRN: How to use Facebook For Business
SBRN: How to use Facebook For BusinessSBRN: How to use Facebook For Business
SBRN: How to use Facebook For BusinessBirgit Pauli-Haack
 
Legado de un Paciente Critico Terminal UP Med
Legado de un Paciente Critico Terminal UP MedLegado de un Paciente Critico Terminal UP Med
Legado de un Paciente Critico Terminal UP MedJorge Sinclair
 
Cuadro sinóptico
Cuadro sinópticoCuadro sinóptico
Cuadro sinópticolreina15
 
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...GLG (Gerson Lehrman Group)
 

Viewers also liked (20)

Building an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twistedBuilding an inflight entertainment system controller in twisted
Building an inflight entertainment system controller in twisted
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs Scalability
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
Python twisted
Python twistedPython twisted
Python twisted
 
আহত সাপ
আহত সাপআহত সাপ
আহত সাপ
 
Factoryweb Agencias Publicidad
Factoryweb Agencias PublicidadFactoryweb Agencias Publicidad
Factoryweb Agencias Publicidad
 
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en Twitter
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en TwitterLas 5 preocupaciones en Twitter sobre la salida de Claudio Palma en Twitter
Las 5 preocupaciones en Twitter sobre la salida de Claudio Palma en Twitter
 
Crm
CrmCrm
Crm
 
Oto cycles 1
Oto cycles 1Oto cycles 1
Oto cycles 1
 
47. EPISTOLA 2CORINTENI ORIGINAL ANTIC -FACSIMIL
47. EPISTOLA  2CORINTENI  ORIGINAL ANTIC -FACSIMIL47. EPISTOLA  2CORINTENI  ORIGINAL ANTIC -FACSIMIL
47. EPISTOLA 2CORINTENI ORIGINAL ANTIC -FACSIMIL
 
Proyecto daphne es
Proyecto daphne esProyecto daphne es
Proyecto daphne es
 
SBRN: How to use Facebook For Business
SBRN: How to use Facebook For BusinessSBRN: How to use Facebook For Business
SBRN: How to use Facebook For Business
 
Legado de un Paciente Critico Terminal UP Med
Legado de un Paciente Critico Terminal UP MedLegado de un Paciente Critico Terminal UP Med
Legado de un Paciente Critico Terminal UP Med
 
Cuadro sinóptico
Cuadro sinópticoCuadro sinóptico
Cuadro sinóptico
 
Instrumentos
InstrumentosInstrumentos
Instrumentos
 
Presentación holacracia
Presentación holacraciaPresentación holacracia
Presentación holacracia
 
Cartas a julieta
Cartas a julietaCartas a julieta
Cartas a julieta
 
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...
China eCommerce Market Analysis Report 2013 – Chapter 2: Characteristics and ...
 
Leading HR Practices
Leading HR PracticesLeading HR Practices
Leading HR Practices
 
Bombas centrífugas
Bombas centrífugasBombas centrífugas
Bombas centrífugas
 

Similar to WTF is Twisted?

Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyKyle Drake
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web FrameworkDaniel Woods
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Junichi Ishida
 
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...E. Camden Fisher
 
Puppet Camp New York 2014: Streamlining Puppet Development Workflow
Puppet Camp New York 2014: Streamlining Puppet Development Workflow Puppet Camp New York 2014: Streamlining Puppet Development Workflow
Puppet Camp New York 2014: Streamlining Puppet Development Workflow Puppet
 
Steamlining your puppet development workflow
Steamlining your puppet development workflowSteamlining your puppet development workflow
Steamlining your puppet development workflowTomas Doran
 
Kuby, ActiveDeployment for Rails Apps
Kuby, ActiveDeployment for Rails AppsKuby, ActiveDeployment for Rails Apps
Kuby, ActiveDeployment for Rails AppsCameron Dutro
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Sam Muhanguzi
 
Cassandra and Docker Lessons Learned
Cassandra and Docker Lessons LearnedCassandra and Docker Lessons Learned
Cassandra and Docker Lessons LearnedDataStax Academy
 
Writing Better Haskell
Writing Better HaskellWriting Better Haskell
Writing Better Haskellnkpart
 
Habitat Overview
Habitat OverviewHabitat Overview
Habitat OverviewMandi Walls
 
Containers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellContainers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellEugene Fedorenko
 

Similar to WTF is Twisted? (20)

Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
 
Stackato v3
Stackato v3Stackato v3
Stackato v3
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.
 
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...
CT Software Developers Meetup: Using Docker and Vagrant Within A GitHub Pull ...
 
Stackato v4
Stackato v4Stackato v4
Stackato v4
 
Puppet Camp New York 2014: Streamlining Puppet Development Workflow
Puppet Camp New York 2014: Streamlining Puppet Development Workflow Puppet Camp New York 2014: Streamlining Puppet Development Workflow
Puppet Camp New York 2014: Streamlining Puppet Development Workflow
 
Steamlining your puppet development workflow
Steamlining your puppet development workflowSteamlining your puppet development workflow
Steamlining your puppet development workflow
 
Kuby, ActiveDeployment for Rails Apps
Kuby, ActiveDeployment for Rails AppsKuby, ActiveDeployment for Rails Apps
Kuby, ActiveDeployment for Rails Apps
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
About Clack
About ClackAbout Clack
About Clack
 
Stackato
StackatoStackato
Stackato
 
Gwt and rpc use 2007 1
Gwt and rpc use 2007 1Gwt and rpc use 2007 1
Gwt and rpc use 2007 1
 
Stackato v6
Stackato v6Stackato v6
Stackato v6
 
Cassandra and Docker Lessons Learned
Cassandra and Docker Lessons LearnedCassandra and Docker Lessons Learned
Cassandra and Docker Lessons Learned
 
Writing Better Haskell
Writing Better HaskellWriting Better Haskell
Writing Better Haskell
 
Stackato v5
Stackato v5Stackato v5
Stackato v5
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Habitat Overview
Habitat OverviewHabitat Overview
Habitat Overview
 
Containers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshellContainers, Serverless and Functions in a nutshell
Containers, Serverless and Functions in a nutshell
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 

WTF is Twisted?

  • 1. WTF is Twisted? (or: Owl Amongst The Ponies)
  • 2. About HawkOwl • hawkowl@atleastfornow.net • @hawkieowl on Twitter • hawkowl on GitHub, Keybase & ThoughtStreams • PGP Key Fingerprint:
 2100 5027 897E C8AE 1D94
 A905 2308 B479 D392 4A11 • Twisted Core Committer and Release Manager (13.2 & 14.0) • Is not actually an owl
  • 3. Twisted in One Slide • Twisted is a framework for writing network applications in Python • Best known for “Deferreds”, Twisted’s async abstraction • Contains protocol implementations for HTTP, SMTP, IMAP, DNS, etc.
  • 4. Why would you want to use Twisted? • Higher performance in some common situations • Stable, mature codebase • Protocol implementations for lots of things • High test coverage • Great community consisting of excellent individuals who do excellent work
  • 5. What makes Twisted especially different from other projects? • Twisted has a reputation for being the “black sheep” in the Python community, mostly because we do things “weirdly” and “hard” • But, surprise! It turns out the Twisted developers were right all along (see: asyncio) • Different set of principals, from both the longevity of the project and their specific problems
  • 6. The Tenets of Twisted (the time-tested, battle-hardened principals of the Twisted project, as interpreted by HawkOwl)
  • 7. Subclassing is bad. Composition is the new inheritance!
  • 8. Multiple inheritance is really bad. Handy hint: If you’ve written the word “super”, it’s already too late.
  • 9. Time-based releases are king. For large, evolving frameworks, it’s better to gradually change than have a massive app migration effort.
  • 10. Early APIs > No APIS You won’t know how your API works in the real world until other people use it. You can always deprecate it later.
  • 11. All code needs tests. No exceptions. It doesn’t matter if you’re fixing an urgent release regression - an eye on coverage saves you a lot of time later.
  • 12. All code needs reviewing. No exceptions. Code review is invaluable, even if it does descend into bikeshedding if they can’t find anything wrong.
  • 13. Only bad APIs can’t be unit tested. Can’t unit test your API? Too bad, time to refactor it.
  • 14. Build slaves are amazing. Test your code on everything. Virtual machines are cheap, compatibility problems down the line are not.
  • 15. –David Reid, Glyph, et al “Call a function with some arguments and inspect some return values.”
  • 16. How Twisted Works (a short, mostly-correct overview)
  • 17. The Event Loop (Spin me right round, baby, right round)
  • 18. The Reactor • Twisted, being an event-driven framework, provides an event loop, or “reactor”. • This is an infinite loop, wrapped around a blocking call that waits until some I/O is ready • Once the I/O is ready, this fires off an event to run the code that was waiting for it • Runs other tasks while I/O blocked tasks are waiting
  • 19. Using the Reactor • To utilise the reactor, you use Deferreds. • Deferreds are an “IOU” for an actual result sometime in the future • A Deferred contains a callback chain, a series of functions run in sequence after it gets a result • Deferreds get their results from events occurring - such as I/O being received or some task being finished
  • 20. Benefits • For I/O bound applications, allows you to efficiently use CPU resources, as the reactor runs other things in the meantime • Integration with common event loops - for example, GTK or QT, to use your Twisted code into your GTK or QT applications
  • 21. The Callback Chain (Hey, I just met you, and this is crazy,
 but here’s a function, so call it maybe?)
  • 22. The Callback Chain • The easiest way to understand the callback chain is to visualise it as a production line. • A production line is made up of discrete blocks - each doing a separate thing. • Let’s imagine a such a production line…
  • 23. Lets say that we are building a toy car, and we need to do the following: 1. Create toy car body from materials 2. Paint racing stripes on car body 3. Add wheels to the car body 4. Put the completed car in a box
  • 24. Here is how we would do that in psuedo-code Deferreds: ! ! d = Deferred()! !d.addCallback(buildCarBody)! d.addCallback(paintStripes)! d.addCallback(addWheels)! d.addCallback(placeInBox)! # Start the callback chain! d.callback(rawMaterials)
  • 25. Deferreds • Each function in the chain is called with the result of the previous one as its first argument • Functions in the callback chain can return either a result or a Deferred that fires with a result sometime in the future
  • 26. Lists of Deferreds • If you have several Deferred operations to do at the same time, and want your callback to fire only when they are all done, use DeferredList.! • Pass it a list of Deferreds, and it will return a Deferred that fires with a list containing the results of each when they have all finished.
  • 27. Error Handling • Error handling is done by errbacks. • Errbacks are like callbacks, but are run when an exception is raised. • An errback will catch all errors that occur on the chain before it.
  • 28. Deferred Benefits • Forces you to break up your logic into sections, broken up over external interface accesses • Encourages reuse, as these sections quite commonly do one thing to an input and return it • Can be cancelled (eg. if a client disconnected and you don’t care about the result anymore)
  • 29. Deferred Benefits • Discourages global mutable state by having different execution threads share the same global state • No global mutable state means you can scale easier • If your global state is databases, just spin up more Twisted instances to use all your CPUs
  • 30. Extending the Callback Chain (Because sometimes things like to do other things)
  • 31. Deferreds returning Deferreds • Deferreds can contain their own callback chain - meaning that one Deferred returned may have several callbacks being called inside it • This is invisible to the “top level” of callbacks • You can extend your callback chain at any time
  • 32. What can Twisted do? (Enough of the boring stuff!)
  • 33. Web • Klein, a Flask-like API in Twisted • Saratoga, a HTTP API framework • Autobahn, a Websockets implementation • Hendrix, a Django deployment framework • Static file serving: 
 twistd -n web --port tcp:8080 --path /tmp
  • 34. Klein (Flask in Twisted) from klein import Klein! app = Klein()! ! @app.route('/')! def home(request):! return 'Hello, world!'! ! app.run("localhost", 8080)
  • 35. Saratoga (HTTP API) {! "metadata": {! "name": “APIExample", "versions": [1]! },! "endpoints": [{! ! ! "endpoint": “example", "getProcessors": [! {"versions": [1]}! ]}! ]}! from saratoga.api import SaratogaAPI! import json! ! class APIExample(object):! class v1(object):! def example_GET(self, request, params):! return {"hello": "world"}! ! api = SaratogaAPI(APIExample, json.load(open("apidef.json")))! api.run()
  • 36. Email • Complete SMTP and ESMTP server and clients • POP3 and IMAP4 servers and clients • Support for TLS-secured email out of the box
 
 For more info, see:
 http://twistedmatrix.com/documents/ current/mail/index.html
  • 37. DNS • A caching, recursive DNS server out of the box
 twistd -n dns -c —port 10053 --recursive • DNS client APIs • DNS server toolkit
 
 For more info, see:
 http://twistedmatrix.com/documents/ current/names/howto/custom-server.html
  • 38. Chat • IRC Server
 twistd -n words --irc-port tcp:8400 --group roomname --auth memory:usr:pass • IRC client (for making IRC bots) • XMPP client
 
 For more info, see: 
 http://twistedmatrix.com/documents/ current/words/examples/
  • 39. Want to know more? • Twisted Docs
 http://twistedmatrix.com/documents/current/ • Iffy’s Twisted FTW
 http://iffycan.com/twistedftw/ • HawkOwl’s Technicals
 http://technicals.atleastfornow.net/