SlideShare a Scribd company logo
1 of 25
Download to read offline
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

More Related Content

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

Featured

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 HubspotMarius Sescu
 
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 ChatGPTExpeed Software
 
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 EngineeringsPixeldarts
 
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 HealthThinkNow
 
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.pdfmarketingartwork
 
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 2024Neil Kimberley
 
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)contently
 
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 2024Albert Qian
 
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 InsightsKurio // The Social Media Age(ncy)
 
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 2024Search Engine Journal
 
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 summarySpeakerHub
 
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 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 Tessa Mero
 
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 IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
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 managementMindGenius
 
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...RachelPearson36
 

Featured (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