SlideShare a Scribd company logo
Python Twisted




Mahendra M
@mahendra




         http://creativecommons.org/licenses/by-sa/3.0/

                        
Methods of concurrency
   Workers
              Threads and processes
   Event driven


    Let us examine this with the case of a web server




                             
Worker model

request   dispatch()   worker_1()


                                    read(fp)

                                     db_rd()

                                     db_wr()

                                    sock_wr()




                       worker_n()

                  
Worker model

request   dispatch()     worker_1()


                                      read(fp)

                       BLOCKING!!db_rd()
                                       db_wr()

                                      sock_wr()




                         worker_n()

                  
How does it scale ?
   A worker gets CPU when it is not blocking
   When it makes a blocking call, it sleeps till the sys­
     call is requested
   At this time another worker gets CPU
   Worker might block before it completes it's 
     allocated timeslice.
   This model has worked great and still works great
   Eg: Apache, Squid

                        
Overheads
   Worker management
              Thread creation
              Process creation and management
              Synchronization
              Scheduling (though this is left to OS)
   More system calls for blocking operations




                               
Event Driven Code
   Non blocking code blocks
   Code execution on events
              Data on sockets, timer, new connection
   Execution triggered from an event loop
   Full use of CPU timeslice




                              
Visually ...
                                        Non blocking functions



event_1                                     hdler_1()



event_2         block_on_events( .. )       hdler_2()



          Events are posted



event_n                                     hdler_n()




                          
Visually ...
                                 Non blocking functions



event_1                              hdler_1()            ev()



event_2      block_on_events()       hdler_2()



          Events are posted



event_n                              hdler_n()




                          
Web Server
                             Non blocking functions


 request                         open(fp)             reg()


 opened                           parse()


              event_loop()      read_sql()            reg()


sql_read                         wri_sql()            reg()


sql_writ                         sock_wr()            reg()

responded                         close()

                     
Event Driven Designs
   Nginx, Tornado
   Varnish
   Memcached
   OS support
              epoll – Linux
              kqueue – BSDs




                                
Event Driven Libraries
   Libevent
   Python­twisted
   Java NIO
                Apache MINA, Tomcat (not default)
                Jetty
   QT




                               
Drawbacks
   Tougher to code, design and maintain
   Workers required to make use of multiple CPUs
   All callbacks must be non­blocking
              Tough to get non­blocking libraries for all modules
   No isolation
              A block in any event loop can freeze everything




                              
Python Twisted
   Event driven programming framework
   MIT licensed
   8 years old and stable
   Support for large number of protocols
              Client and server support
              HTTP – SOAP, REST, CouchDB, XMLRPC, ....
              Sockets, TCP/IP, Multicast, TLS, SSH, IMAP …
              SMTP, NNTP, FTP, Memcached, AMQP, XMPP, ...

                              
Deferred
   The central concept of twisted
   A callback returns a deferred to indicate that the job 
     is not done yet.
   The caller can add callbacks to a deferred.
   The callbacks are invoked then the job is done


    Eh ?


                        
Deferred example
from twisted.internet import reactor

# Define a success callback
def cb( arg1, arg2 ):
    print ”Timeout after %d %s” % ( arg1, arg2 )

# Define an error callback
def eb( error ):
    Print ”error %s” % error

# Invoke a non blocking task
deferred = someTimeout( 4 )

# Register the callbacks on the returned deferred
deferred.addCallback( cb, 4, 'twisted is great' )
deferred.addErrback( eb )

# Run the event loop
reactor.run()
                   
Twisted Server

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class QOTD(Protocol):
    def connectionMade(self):
        self.transport.write("Welcomern")
        self.transport.loseConnection()

# Next lines are magic:
factory = Factory()
factory.protocol = QOTD

# 8007 is the port you want to run under.
reactor.listenTCP(8007, factory)
reactor.run()



                       
Deferred chaining
   A callback can register and return another deferred
   This callback can return another deferred
   In short we have a deferred chain …
   Web server example:




                       
Deferred Chaining




         
Advanced twisted
   Twisted application support
              Mixing and matching twisted applications
   Command line 'twistd' runner
              Pre­defined twisted apps
              Web, telnet, xmpp, dns, conch (ssh), mail, …
   Plugin architecture
   Live debugging
   ADBAPI – for RDBMS

                              
Advanced twisted
   Perspective Broker
              RPC and object sharing
              Spreading out servers
   Cred – Authentication framework
   Deferring to threads
   External loops (GTK, QT)
   Streaming support
   MVC framework (Complex. Very complex)

                              
Drawbacks
   Single threaded by design
   Makes use of only one core/CPU
   Need external modules for using multiple CPU
              Run multiple instances of twisted on a box
              num_instances = num_cpus
              Use nginx (HTTP), HAProxy for load balancing




                              
Demos




     
Links
   http://twistedmatrix.com/trac/




                       

More Related Content

PDF
An Introduction to Python Concurrency
PPTX
Network programming in java - PPT
PPT
Java And Multithreading
PPT
Exception Handling in JAVA
PPT
Network programming in Java
PPTX
Dart PPT.pptx
PPTX
Exception handling c++
PPTX
Python Data Structures and Algorithms.pptx
An Introduction to Python Concurrency
Network programming in java - PPT
Java And Multithreading
Exception Handling in JAVA
Network programming in Java
Dart PPT.pptx
Exception handling c++
Python Data Structures and Algorithms.pptx

What's hot (20)

PDF
Introduction to MPI
PDF
PPTX
PHP FUNCTIONS
PPTX
Templates in c++
PDF
C Pointers
PPT
PPTX
Python SQite3 database Tutorial | SQlite Database
PPT
SWITCH CASE STATEMENT IN C
PPTX
Css box-sizing
PDF
Unit-4 networking basics in java
PDF
PPTX
Java string handling
PPTX
Input output files in java
PPT
File handling
PPT
Chap2 2 1
PDF
Genesis and Overview of Java
PPT
JavaScript Control Statements I
PDF
Java Course 8: I/O, Files and Streams
Introduction to MPI
PHP FUNCTIONS
Templates in c++
C Pointers
Python SQite3 database Tutorial | SQlite Database
SWITCH CASE STATEMENT IN C
Css box-sizing
Unit-4 networking basics in java
Java string handling
Input output files in java
File handling
Chap2 2 1
Genesis and Overview of Java
JavaScript Control Statements I
Java Course 8: I/O, Files and Streams
Ad

Viewers also liked (17)

PPTX
Asynchronous Python with Twisted
ODP
Kyua and Jenkins: Testing Framework for BSD
PDF
Обзор фреймворка Twisted
PDF
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
PDF
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
PDF
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
PDF
An Introduction to Twisted
PDF
WTF is Twisted?
PPTX
Twisted pair cable
PPTX
The Onward Journey: Porting Twisted to Python 3
PDF
Implementing microservices tracing with spring cloud and zipkin (spring one)
PDF
Consumer Driven Contracts and Your Microservice Architecture
PDF
Visual Design with Data
PDF
Build Features, Not Apps
PDF
2015 Upload Campaigns Calendar - SlideShare
PPTX
What to Upload to SlideShare
PDF
Getting Started With SlideShare
Asynchronous Python with Twisted
Kyua and Jenkins: Testing Framework for BSD
Обзор фреймворка Twisted
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
An Introduction to Twisted
WTF is Twisted?
Twisted pair cable
The Onward Journey: Porting Twisted to Python 3
Implementing microservices tracing with spring cloud and zipkin (spring one)
Consumer Driven Contracts and Your Microservice Architecture
Visual Design with Data
Build Features, Not Apps
2015 Upload Campaigns Calendar - SlideShare
What to Upload to SlideShare
Getting Started With SlideShare
Ad

Similar to Python twisted (20)

PPTX
Copper: A high performance workflow engine
PDF
Nginx Internals
PPT
Server side JavaScript: going all the way
KEY
Servers with Event Machine - David Troy - RailsConf 2011
PDF
Virtualizing Java in Java (jug.ru)
ODP
Node js lecture
ODP
Introduce about Nodejs - duyetdev.com
PDF
Silicon Valley JUG: JVM Mechanics
PPTX
Scaling django
PDF
PDF
20140513_jeffyang_demo_openstack
PDF
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
PDF
A Scalable I/O Manager for GHC
PDF
Scaling Django with gevent
PPT
Nodejs Intro Part One
PDF
Automated Application Management with SaltStack
PDF
Container orchestration from theory to practice
PDF
Implementações paralelas
PDF
LibOS as a regression test framework for Linux networking #netdev1.1
PPT
A Practical Event Driven Model
Copper: A high performance workflow engine
Nginx Internals
Server side JavaScript: going all the way
Servers with Event Machine - David Troy - RailsConf 2011
Virtualizing Java in Java (jug.ru)
Node js lecture
Introduce about Nodejs - duyetdev.com
Silicon Valley JUG: JVM Mechanics
Scaling django
20140513_jeffyang_demo_openstack
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
A Scalable I/O Manager for GHC
Scaling Django with gevent
Nodejs Intro Part One
Automated Application Management with SaltStack
Container orchestration from theory to practice
Implementações paralelas
LibOS as a regression test framework for Linux networking #netdev1.1
A Practical Event Driven Model

Recently uploaded (20)

PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
1. Introduction to Computer Programming.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
Mushroom cultivation and it's methods.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Hybrid model detection and classification of lung cancer
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
A novel scalable deep ensemble learning framework for big data classification...
Heart disease approach using modified random forest and particle swarm optimi...
Assigned Numbers - 2025 - Bluetooth® Document
SOPHOS-XG Firewall Administrator PPT.pptx
Chapter 5: Probability Theory and Statistics
1. Introduction to Computer Programming.pptx
Unlocking AI with Model Context Protocol (MCP)
Zenith AI: Advanced Artificial Intelligence
Mushroom cultivation and it's methods.pdf
A comparative study of natural language inference in Swahili using monolingua...
Hybrid model detection and classification of lung cancer
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
Hindi spoken digit analysis for native and non-native speakers
1 - Historical Antecedents, Social Consideration.pdf
A comparative analysis of optical character recognition models for extracting...
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Tartificialntelligence_presentation.pptx
Enhancing emotion recognition model for a student engagement use case through...
A novel scalable deep ensemble learning framework for big data classification...

Python twisted

  • 1. Python Twisted Mahendra M @mahendra http://creativecommons.org/licenses/by-sa/3.0/    
  • 2. Methods of concurrency  Workers  Threads and processes  Event driven Let us examine this with the case of a web server    
  • 3. Worker model request dispatch() worker_1() read(fp) db_rd() db_wr() sock_wr() worker_n()    
  • 4. Worker model request dispatch() worker_1() read(fp) BLOCKING!!db_rd() db_wr() sock_wr() worker_n()    
  • 5. How does it scale ?  A worker gets CPU when it is not blocking  When it makes a blocking call, it sleeps till the sys­ call is requested  At this time another worker gets CPU  Worker might block before it completes it's  allocated timeslice.  This model has worked great and still works great  Eg: Apache, Squid    
  • 6. Overheads  Worker management  Thread creation  Process creation and management  Synchronization  Scheduling (though this is left to OS)  More system calls for blocking operations    
  • 7. Event Driven Code  Non blocking code blocks  Code execution on events  Data on sockets, timer, new connection  Execution triggered from an event loop  Full use of CPU timeslice    
  • 8. Visually ... Non blocking functions event_1 hdler_1() event_2 block_on_events( .. ) hdler_2() Events are posted event_n hdler_n()    
  • 9. Visually ... Non blocking functions event_1 hdler_1() ev() event_2 block_on_events() hdler_2() Events are posted event_n hdler_n()    
  • 10. Web Server Non blocking functions request open(fp) reg() opened parse() event_loop() read_sql() reg() sql_read wri_sql() reg() sql_writ sock_wr() reg() responded close()    
  • 11. Event Driven Designs  Nginx, Tornado  Varnish  Memcached  OS support  epoll – Linux  kqueue – BSDs    
  • 12. Event Driven Libraries  Libevent  Python­twisted  Java NIO  Apache MINA, Tomcat (not default)  Jetty  QT    
  • 13. Drawbacks  Tougher to code, design and maintain  Workers required to make use of multiple CPUs  All callbacks must be non­blocking  Tough to get non­blocking libraries for all modules  No isolation  A block in any event loop can freeze everything    
  • 14. Python Twisted  Event driven programming framework  MIT licensed  8 years old and stable  Support for large number of protocols  Client and server support  HTTP – SOAP, REST, CouchDB, XMLRPC, ....  Sockets, TCP/IP, Multicast, TLS, SSH, IMAP …  SMTP, NNTP, FTP, Memcached, AMQP, XMPP, ...    
  • 15. Deferred  The central concept of twisted  A callback returns a deferred to indicate that the job  is not done yet.  The caller can add callbacks to a deferred.  The callbacks are invoked then the job is done Eh ?    
  • 16. Deferred example from twisted.internet import reactor # Define a success callback def cb( arg1, arg2 ): print ”Timeout after %d %s” % ( arg1, arg2 ) # Define an error callback def eb( error ): Print ”error %s” % error # Invoke a non blocking task deferred = someTimeout( 4 ) # Register the callbacks on the returned deferred deferred.addCallback( cb, 4, 'twisted is great' ) deferred.addErrback( eb ) # Run the event loop reactor.run()    
  • 17. Twisted Server from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class QOTD(Protocol): def connectionMade(self): self.transport.write("Welcomern") self.transport.loseConnection() # Next lines are magic: factory = Factory() factory.protocol = QOTD # 8007 is the port you want to run under. reactor.listenTCP(8007, factory) reactor.run()    
  • 18. Deferred chaining  A callback can register and return another deferred  This callback can return another deferred  In short we have a deferred chain …  Web server example:    
  • 20. Advanced twisted  Twisted application support  Mixing and matching twisted applications  Command line 'twistd' runner  Pre­defined twisted apps  Web, telnet, xmpp, dns, conch (ssh), mail, …  Plugin architecture  Live debugging  ADBAPI – for RDBMS    
  • 21. Advanced twisted  Perspective Broker  RPC and object sharing  Spreading out servers  Cred – Authentication framework  Deferring to threads  External loops (GTK, QT)  Streaming support  MVC framework (Complex. Very complex)    
  • 22. Drawbacks  Single threaded by design  Makes use of only one core/CPU  Need external modules for using multiple CPU  Run multiple instances of twisted on a box  num_instances = num_cpus  Use nginx (HTTP), HAProxy for load balancing    
  • 23. Demos    
  • 24. Links  http://twistedmatrix.com/trac/