SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
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/




                       

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Generics
GenericsGenerics
Generics
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
String in java
String in javaString in java
String in java
 

Andere mochten auch

Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with TwistedAdam Englander
 
Kyua and Jenkins: Testing Framework for BSD
Kyua and Jenkins: Testing Framework for BSDKyua and Jenkins: Testing Framework for BSD
Kyua and Jenkins: Testing Framework for BSDCraig Rodrigues
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedPython Meetup
 
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с CodeceptionWebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с CodeceptionWebCamp
 
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...WebCamp
 
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...WebCamp
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Twisted pair cable
Twisted pair cableTwisted pair cable
Twisted pair cableilakkiya
 
The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3The Onward Journey: Porting Twisted to Python 3
The Onward Journey: Porting Twisted to Python 3Craig Rodrigues
 
Implementing microservices tracing with spring cloud and zipkin (spring one)
Implementing microservices tracing with spring cloud and zipkin (spring one)Implementing microservices tracing with spring cloud and zipkin (spring one)
Implementing microservices tracing with spring cloud and zipkin (spring one)Reshmi Krishna
 
Consumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureConsumer Driven Contracts and Your Microservice Architecture
Consumer Driven Contracts and Your Microservice ArchitectureMarcin Grzejszczak
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Andere mochten auch (17)

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

Ähnlich wie Python twisted

Copper: A high performance workflow engine
Copper: A high performance workflow engineCopper: A high performance workflow engine
Copper: A high performance workflow enginedmoebius
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx InternalsJoshua Zhu
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011David Troy
 
Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)aragozin
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
20140513_jeffyang_demo_openstack
20140513_jeffyang_demo_openstack20140513_jeffyang_demo_openstack
20140513_jeffyang_demo_openstackJeff Yang
 
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...Jeff Yang
 
A Scalable I/O Manager for GHC
A Scalable I/O Manager for GHCA Scalable I/O Manager for GHC
A Scalable I/O Manager for GHCJohan Tibell
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with geventMahendra M
 
Automated Application Management with SaltStack
Automated Application Management with SaltStackAutomated Application Management with SaltStack
Automated Application Management with SaltStackinovex GmbH
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelasWillian Molinari
 
LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1Hajime Tazaki
 
A Practical Event Driven Model
A Practical Event Driven ModelA Practical Event Driven Model
A Practical Event Driven ModelXi Wu
 

Ähnlich wie Python twisted (20)

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

Kürzlich hochgeladen

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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/