SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
More than just a pretty web framework:
        the Tornado IOLoop


             Gavin M. Roy
About myYearbook
According to comScore,
myYearbook is one of the 25 most-
trafficked sites in the United States
as measured by page views, by
minutes, and by minutes per visitor
per month.




              http://www.myyearbook.com/careers
PyCon 2012                                  Follow me on Twitter: @Crad
Tornado @
                    myYearbook
       • At myYearbook, we used Tornado in high-
             request-velocity applications.
             • Web apps
             • Finite State Machine Game Server
       •     Take what you need? We do.


PyCon 2012                                    Follow me on Twitter: @Crad
Async Network
                   Programming
       • Core revolves around an I/O loop
        • Let the Operating System indicate when
               to read, when to write and when there
               are errors on sockets.
             • select, poll, epoll (Linux), kqueue (BSD)
       • Callback-Passing Style
PyCon 2012                                     Follow me on Twitter: @Crad
Async Network
              Programming




PyCon 2012               Follow me on Twitter: @Crad
Callback Passing Style
def start(foo):

      # Do stuff with foo and when done call the next function
      stuff(callback=next_step, data=foo);

def next_step(bar):

      # Call more_stuff to parse bar
      more_stuff(callback=last_step, data=bar);

def last_step(baz):

      # Send the response
      send_response(baz)

      # Let our handler know we are done
      finish()


PyCon 2012                                          Follow me on Twitter: @Crad
tornado.IOLoop
       • Core of Tornado’s network stack
       • Fast and easy to use
       • Single instance per process        Works on windows but
                                            not supported.

                                            C-Based epoll, not required


       • Cross-platform
       • Easy to read source: http://goo.gl/VFeAF
       • Used for client libraries & server
             applications
PyCon 2012                                Follow me on Twitter: @Crad
tornado.IOStream

       • Convenient utility class for dealing with the
             IOLoop
       • Does most of the work for you
       • This too is for use by clients and server
             applications


PyCon 2012                                 Follow me on Twitter: @Crad
IOStream: How to read
       • read_until_regex
             (regex, callback)

       • read_until
             (delimiter, callback)

       • read_bytes
             (num_bytes, callback,
             streaming_callback=None)

       • read_until_close
             (callback,
             streaming_callback=None)


PyCon 2012                              Follow me on Twitter: @Crad
IOStream: What’s Going On?




      reading(), writing(), closed()
PyCon 2012                   Follow me on Twitter: @Crad
Serious
  Business Uses
       SSL

             And that’s why SSLIOStream Exists.
PyCon 2012                                  Follow me on Twitter: @Crad
tornado.netutil.TCPServer



PyCon 2012              Follow me on Twitter: @Crad
Hello Async World
from tornado import ioloop
from tornado import netutil

class EchoServer(netutil.TCPServer):

      def handle_stream(self, stream, address):
          self._stream = stream
          self._read_line()

      def _read_line(self):
          self._stream.read_until('n', self._handle_read)

      def _handle_read(self, data_in):
          self._stream.write('You sent: %s' % data_in)
          self._read_line()

if __name__ == '__main__':
    server = EchoServer()
    server.listen(2007)
    ioloop.IOLoop.instance().start()              Source: http://goo.gl/eB7z4
PyCon 2012                                            Follow me on Twitter: @Crad
What just happened?


              tornado.stack_context.StackContext




                        “Slight Magic”


PyCon 2012                                 Follow me on Twitter: @Crad
Diving Deeper




PyCon 2012               Follow me on Twitter: @Crad
tornado.IOLoop
       • IOLoop.instance()
       • ioloop.add_handler
             (fd, handler, events)

       • ioloop.update_handler
             (fd, handler, events)

       • ioloop.remove_handler(fd)
PyCon 2012                           Follow me on Twitter: @Crad
Events?




             READ, WRITE, ERROR
PyCon 2012                  Follow me on Twitter: @Crad
“Example”
import socket
from tornado import ioloop

def on_events(fd, events, error=None):

      if events & ioloop.IOLoop.READ:
          print 'Socket read: %r' % fd.recv(1024)

      if events & ioloop.IOLoop.ERROR:
          print 'Error received: %r' % error

      if events & ioloop.IOLoop.WRITE:
          pass

_ioloop = ioloop.IOLoop.instance()
fd = socket.socket() # Other stuff needs to be done here
events_desired = ioloop.IOLoop.READ | ioloop.IOLoop.ERROR
_ioloop.add_handler(fd, on_events, events_desired)
_ioloop.start()

PyCon 2012                                          Follow me on Twitter: @Crad
Timers     add_timeout returns a
                                    reference

                                    deadline can be unix
                                    timestamp or a
                                    datetime.timedelta




       • add_timeout
             (deadline, callback)

       • remove_timeout
             (timeout)




PyCon 2012                          Follow me on Twitter: @Crad
add_callback(callback)
PyCon 2012            Follow me on Twitter: @Crad
“Pythonic”
             Simplification


PyCon 2012               Follow me on Twitter: @Crad
tornado.gen
             for coding not in Callback Passing Style:

@gen.engine
def foo():
    http_client = AsyncHTTPClient()
    response1, response2 = yield [gen.Task(http_client.fetch,
                                           url1),
                                  gen.Task(http_client.fetch,
                                           url2)]




PyCon 2012                                        Follow me on Twitter: @Crad
tornado.platform.twisted
PyCon 2012             Follow me on Twitter: @Crad
Last Thoughts

       • Single threaded, use processes
       • Watch out for resource contention
       • Benchmark your application
       • Fork work to remote workers
        • multiprocessing.reduction
PyCon 2012                             Follow me on Twitter: @Crad
multiprocessing.reduction:
# Main process
from multiprocessing.reduction import reduce_handle

h = reduce_handle(client_socket.fileno())

pipe_to_worker.send(h) #instance of multiprocessing.Pipe

# Worker process
from multiprocessing.reduction import rebuild_handle

h = pipe.recv()
fd = rebuild_handle(h)
client_socket = socket.fromfd(fd, socket.AF_INET,
                              socket.SOCK_STREAM)
client_socket.send("hello from the worker processrn")



                      Questions?
PyCon 2012                                        Follow me on Twitter: @Crad

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Empfohlen

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

More than just a pretty web framework: the Tornado IOLoop

  • 1. More than just a pretty web framework: the Tornado IOLoop Gavin M. Roy
  • 2. About myYearbook According to comScore, myYearbook is one of the 25 most- trafficked sites in the United States as measured by page views, by minutes, and by minutes per visitor per month. http://www.myyearbook.com/careers PyCon 2012 Follow me on Twitter: @Crad
  • 3. Tornado @ myYearbook • At myYearbook, we used Tornado in high- request-velocity applications. • Web apps • Finite State Machine Game Server • Take what you need? We do. PyCon 2012 Follow me on Twitter: @Crad
  • 4. Async Network Programming • Core revolves around an I/O loop • Let the Operating System indicate when to read, when to write and when there are errors on sockets. • select, poll, epoll (Linux), kqueue (BSD) • Callback-Passing Style PyCon 2012 Follow me on Twitter: @Crad
  • 5. Async Network Programming PyCon 2012 Follow me on Twitter: @Crad
  • 6. Callback Passing Style def start(foo): # Do stuff with foo and when done call the next function stuff(callback=next_step, data=foo); def next_step(bar): # Call more_stuff to parse bar more_stuff(callback=last_step, data=bar); def last_step(baz): # Send the response send_response(baz) # Let our handler know we are done finish() PyCon 2012 Follow me on Twitter: @Crad
  • 7. tornado.IOLoop • Core of Tornado’s network stack • Fast and easy to use • Single instance per process Works on windows but not supported. C-Based epoll, not required • Cross-platform • Easy to read source: http://goo.gl/VFeAF • Used for client libraries & server applications PyCon 2012 Follow me on Twitter: @Crad
  • 8. tornado.IOStream • Convenient utility class for dealing with the IOLoop • Does most of the work for you • This too is for use by clients and server applications PyCon 2012 Follow me on Twitter: @Crad
  • 9. IOStream: How to read • read_until_regex (regex, callback) • read_until (delimiter, callback) • read_bytes (num_bytes, callback, streaming_callback=None) • read_until_close (callback, streaming_callback=None) PyCon 2012 Follow me on Twitter: @Crad
  • 10. IOStream: What’s Going On? reading(), writing(), closed() PyCon 2012 Follow me on Twitter: @Crad
  • 11. Serious Business Uses SSL And that’s why SSLIOStream Exists. PyCon 2012 Follow me on Twitter: @Crad
  • 12. tornado.netutil.TCPServer PyCon 2012 Follow me on Twitter: @Crad
  • 13. Hello Async World from tornado import ioloop from tornado import netutil class EchoServer(netutil.TCPServer): def handle_stream(self, stream, address): self._stream = stream self._read_line() def _read_line(self): self._stream.read_until('n', self._handle_read) def _handle_read(self, data_in): self._stream.write('You sent: %s' % data_in) self._read_line() if __name__ == '__main__': server = EchoServer() server.listen(2007) ioloop.IOLoop.instance().start() Source: http://goo.gl/eB7z4 PyCon 2012 Follow me on Twitter: @Crad
  • 14. What just happened? tornado.stack_context.StackContext “Slight Magic” PyCon 2012 Follow me on Twitter: @Crad
  • 15. Diving Deeper PyCon 2012 Follow me on Twitter: @Crad
  • 16. tornado.IOLoop • IOLoop.instance() • ioloop.add_handler (fd, handler, events) • ioloop.update_handler (fd, handler, events) • ioloop.remove_handler(fd) PyCon 2012 Follow me on Twitter: @Crad
  • 17. Events? READ, WRITE, ERROR PyCon 2012 Follow me on Twitter: @Crad
  • 18. “Example” import socket from tornado import ioloop def on_events(fd, events, error=None): if events & ioloop.IOLoop.READ: print 'Socket read: %r' % fd.recv(1024) if events & ioloop.IOLoop.ERROR: print 'Error received: %r' % error if events & ioloop.IOLoop.WRITE: pass _ioloop = ioloop.IOLoop.instance() fd = socket.socket() # Other stuff needs to be done here events_desired = ioloop.IOLoop.READ | ioloop.IOLoop.ERROR _ioloop.add_handler(fd, on_events, events_desired) _ioloop.start() PyCon 2012 Follow me on Twitter: @Crad
  • 19. Timers add_timeout returns a reference deadline can be unix timestamp or a datetime.timedelta • add_timeout (deadline, callback) • remove_timeout (timeout) PyCon 2012 Follow me on Twitter: @Crad
  • 20. add_callback(callback) PyCon 2012 Follow me on Twitter: @Crad
  • 21. “Pythonic” Simplification PyCon 2012 Follow me on Twitter: @Crad
  • 22. tornado.gen for coding not in Callback Passing Style: @gen.engine def foo(): http_client = AsyncHTTPClient() response1, response2 = yield [gen.Task(http_client.fetch, url1), gen.Task(http_client.fetch, url2)] PyCon 2012 Follow me on Twitter: @Crad
  • 23. tornado.platform.twisted PyCon 2012 Follow me on Twitter: @Crad
  • 24. Last Thoughts • Single threaded, use processes • Watch out for resource contention • Benchmark your application • Fork work to remote workers • multiprocessing.reduction PyCon 2012 Follow me on Twitter: @Crad
  • 25. multiprocessing.reduction: # Main process from multiprocessing.reduction import reduce_handle h = reduce_handle(client_socket.fileno()) pipe_to_worker.send(h) #instance of multiprocessing.Pipe # Worker process from multiprocessing.reduction import rebuild_handle h = pipe.recv() fd = rebuild_handle(h) client_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) client_socket.send("hello from the worker processrn") Questions? PyCon 2012 Follow me on Twitter: @Crad