SlideShare una empresa de Scribd logo
1 de 21
Tornado Web and MongoDB
An Introduction to AsyncMongo


MongoPhilly
2011-04-26

John C. Zablocki
Development Lead, MagazineRadar
Engineering Lead, I’mOK
Agenda
 Evented I/O Web Servers
 Introducing Tornado Web
 Asynchronous Tornado
 Tornado and PyMongo
 Introducing AsyncMongo
 Tornado and AsyncMongo
 Fetching Data with AsyncMongo
 Inserts and Updates with AsyncMongo
 Questions
EVENTED I/O
WEB SERVERS
The C10k Problem
   How does a web server handle 10k
    concurrent requests?
    ◦ Traditional approach is multi-process
      (Apache) or multi-threaded (IIS, Apache)
    ◦ Threads and processes are expensive to
      create, in terms of memory and CPU
    ◦ Scaling web servers such as IIS and
      Apache to thousands of connections
      therefore becomes expensive
Evented I/O Web Servers
   A Single-threaded server with an event loop that
    handles all requests
   By using non-blocking libraries for database, file or
    network access, that single thread is able to handle
    thousands of concurrent connections
   Typically architected around epoll or select() (for non-
    Linux systems)
   Callbacks used to notify thread that non-blocking I/O
    has completed
   Any blocking calls on that thread, will block other
    requests – most platforms are lacking non-blocking
    APIs
   Explained with bunnies at -
    http://www.slideshare.net/simon/evented-io-based-web-
    servers-explained-using-bunnies
Motivation for Evented I/O




Borrowed from a presentation on Node .js by Francisco Treacy (Bing it)
Some Evented I/O Web Servers
   nginx
    ◦   Load balancing and reverse proxying
    ◦   Static and index file serving
    ◦   SSL and TLS support
    ◦   Online reconfiguration
   node.js
    ◦ JavaScript based
    ◦ Built on epoll, kqueue or select
    ◦ Server and app dev framework based on callbacks
   Manos de Mono
    ◦ C# (Mono) based
    ◦ Built on libvent (epoll)
    ◦ Server and app dev framework based on callbacks
   Twisted Web
    ◦ Python based
    ◦ Server and app dev framework
    ◦ Can serve CGI scripts and WSGI applications
INTRODUCING
TORNADO WEB
Tornado Web Overview
   Open source version of the framework
    that powers FriendFeed
   Consists of non-blocking web server and
    web application framework similar to
    Google’s AppEngine
   Includes modules for templating, third-
    party authorization, localization and a
    non-blocking http client, among others
   Install via easy_install tornado
   Runs on Linux, Mac OS X, Windows
    (support is experimental)
Tornado Web Hello, World!
import tornado.web
import tornado.ioloop

class MainHandler(tornado.web.RequestHandler):


         def get(self):
                     self.write("Hello, Tornado World!")


         application = tornado.web.Application([
                     (r"/", MainHandler)
         ])


         if __name__ == "__main__":


                     application.listen(8888)
                     tornado.ioloop.IOLoop.instance().start()
Asynchronous Tornado Web
import tornado.web
import tornado.ioloop

class AsyncHandler(tornado.web.RequestHandler):

       @tornado.web.asynchronous
       def get(self):
                 http = tornado.httpclient.AsyncHTTPClient()
                 http.fetch("http://z.com",callback=self.on_resp)

       def on_resp(self):
                self.write("Hello, Tornado World!")
                self.finish()
PyMongo and Tornado Web
 PyMongo does not provide support for
  working with asynchronous socket
  libraries, such as Tornado or Twisted
 PyMongo does provide connection
  pooling, so similar performance benefits
  may be achieved via multi-threaded code
  sharing a connection
 A driver based on twisted is actively
  being developed -
  https://github.com/fiorix/mongo-async-
  python-driver
PyMongo and Tornado Example
import tornado.web
import tornado.ioloop


import pymongo


class RestaurantListHandler(tornado.web.RequestHandler):


      def get(self):


                 db = pymongo.Connection(“localhost”, 27017)
                 venues = db.venues.find()
                 self.render("List.html", venues=venues)
Introducing AsycnMongo
 AsyncMongo is an asynchronous
  library for accessing MongoDB
 Built on top of Tornado’s ioloop
 Released to the community by bit.ly
 Current version is 0.1.3 and is stable,
  but not feature complete (when
  compared to pymongo)
 Relies on PyMongo’s BSON library
AsyncMongo and Tornado Example
import tornado.web
import tornado.ioloop


import asyncmongo
class RestaurantListHandler(tornado.web.RequestHandler):


       @tornado.web.asynchronous
       def get(self):


                db = asyncmongo.Client(host=“192…”, port=27017, …)
                db.venues.find(limit=10,callback=self.cb)


       def cb(self, response, error):
                self.render("List.html", venues=response)
Fetching Data with AsyncMongo
@tornado.web.asynchronous
def get(self):


         id = self.get_argument("id", None)


         if id != None:
                   spec = { "_id" : pymongo.objectid.ObjectId(id) }


         db = DBFactory.create()
         db.venues.find_one(spec, 
                   callback=lambda r, e: self.render(“Edit.html”, venue=r)
Inserting Data with AsyncMongo
@tornado.web.asynchronous
def post(self):


       doc = {}
       doc["name"] = self.get_argument("name")
       doc["city"] = self.get_argument("city")
       doc["state"] = self.get_argument("state")


       db = DBFactory.create()
       db.venues.insert(doc, callback=self._post_callback)


def _post_callback(self, response, error):


       self.write("Created")
       self.redirect(r"/")
Updating Data with AsyncMongo
@tornado.web.asynchronous
def post(self):


       id = self.get_argument("_id", None)


       doc = {}
       doc["_id"] = pymongo.objectid.ObjectId(id)
       doc["name"] = self.get_argument("name")
       doc["city"] = self.get_argument("city")
       doc["state"] = self.get_argument("state")


       db = DBFactory.create()
       db.venues.update({ "_id" : pymongo.objectid.ObjectId(id) },
                  doc, callback=lambda r, e: self.redirect(r"/"))
Deleting Data with AsyncMongo


@tornado.web.asynchronous
def post(self):


       id = self.get_argument("_id", None)
       db = DBFactory.create()


       db.venues.remove({ "_id" : pymongo.objectid.ObjectId(id) },
                  callback=lambda r, e: self.redirect(r"/"))
Links
 http://www.kegel.com/c10k.html
 http://www.tornadoweb.org/
 https://github.com/facebook/tornado
 https://github.com/bitly/asyncmongo
 http://www.codevoyeur.com
 http://dllhell.net
 http://twitter.com/codevoyeur
 http://about.me/johnzablocki
Questions?

Más contenido relacionado

La actualidad más candente

Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBemptysquare
 
Extending eZ Platform 2.x with Symfony and React
Extending eZ Platform 2.x with Symfony and ReactExtending eZ Platform 2.x with Symfony and React
Extending eZ Platform 2.x with Symfony and ReactPiotr Nalepa
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioCaesar Chi
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsPetr Dvorak
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsRemy Sharp
 
Real World Seaside Applications
Real World Seaside ApplicationsReal World Seaside Applications
Real World Seaside ApplicationsESUG
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetTom Croucher
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 

La actualidad más candente (20)

Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Socket.io
Socket.ioSocket.io
Socket.io
 
New Design of OneRing
New Design of OneRingNew Design of OneRing
New Design of OneRing
 
Extending eZ Platform 2.x with Symfony and React
Extending eZ Platform 2.x with Symfony and ReactExtending eZ Platform 2.x with Symfony and React
Extending eZ Platform 2.x with Symfony and React
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
OneRing @ OSCamp 2010
OneRing @ OSCamp 2010OneRing @ OSCamp 2010
OneRing @ OSCamp 2010
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
What the rack
What the rackWhat the rack
What the rack
 
Real World Seaside Applications
Real World Seaside ApplicationsReal World Seaside Applications
Real World Seaside Applications
 
Analyse Yourself
Analyse YourselfAnalyse Yourself
Analyse Yourself
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Server Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yetServer Side JavaScript - You ain't seen nothing yet
Server Side JavaScript - You ain't seen nothing yet
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 

Similar a Phl mongo-philly-tornado-2011

Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiJackson Tian
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.jsguileen
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Diseño y Desarrollo de APIs
Diseño y Desarrollo de APIsDiseño y Desarrollo de APIs
Diseño y Desarrollo de APIsRaúl Neis
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)Dylan Jay
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneC4Media
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsMongoDB
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmsom_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmwilburlo
 

Similar a Phl mongo-philly-tornado-2011 (20)

Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 
Why Node.js
Why Node.jsWhy Node.js
Why Node.js
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Diseño y Desarrollo de APIs
Diseño y Desarrollo de APIsDiseño y Desarrollo de APIs
Diseño y Desarrollo de APIs
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)
 
Asp.net
Asp.netAsp.net
Asp.net
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Rust: Systems Programming for Everyone
Rust: Systems Programming for EveryoneRust: Systems Programming for Everyone
Rust: Systems Programming for Everyone
 
Webinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.jsWebinar: Building Your First App in Node.js
Webinar: Building Your First App in Node.js
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Guillotina
GuillotinaGuillotina
Guillotina
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
08 ajax
08 ajax08 ajax
08 ajax
 

Último

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
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
 
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 textsMaria Levchenko
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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...Martijn de Jong
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 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
 
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
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Phl mongo-philly-tornado-2011

  • 1. Tornado Web and MongoDB An Introduction to AsyncMongo MongoPhilly 2011-04-26 John C. Zablocki Development Lead, MagazineRadar Engineering Lead, I’mOK
  • 2. Agenda  Evented I/O Web Servers  Introducing Tornado Web  Asynchronous Tornado  Tornado and PyMongo  Introducing AsyncMongo  Tornado and AsyncMongo  Fetching Data with AsyncMongo  Inserts and Updates with AsyncMongo  Questions
  • 4. The C10k Problem  How does a web server handle 10k concurrent requests? ◦ Traditional approach is multi-process (Apache) or multi-threaded (IIS, Apache) ◦ Threads and processes are expensive to create, in terms of memory and CPU ◦ Scaling web servers such as IIS and Apache to thousands of connections therefore becomes expensive
  • 5. Evented I/O Web Servers  A Single-threaded server with an event loop that handles all requests  By using non-blocking libraries for database, file or network access, that single thread is able to handle thousands of concurrent connections  Typically architected around epoll or select() (for non- Linux systems)  Callbacks used to notify thread that non-blocking I/O has completed  Any blocking calls on that thread, will block other requests – most platforms are lacking non-blocking APIs  Explained with bunnies at - http://www.slideshare.net/simon/evented-io-based-web- servers-explained-using-bunnies
  • 6. Motivation for Evented I/O Borrowed from a presentation on Node .js by Francisco Treacy (Bing it)
  • 7. Some Evented I/O Web Servers  nginx ◦ Load balancing and reverse proxying ◦ Static and index file serving ◦ SSL and TLS support ◦ Online reconfiguration  node.js ◦ JavaScript based ◦ Built on epoll, kqueue or select ◦ Server and app dev framework based on callbacks  Manos de Mono ◦ C# (Mono) based ◦ Built on libvent (epoll) ◦ Server and app dev framework based on callbacks  Twisted Web ◦ Python based ◦ Server and app dev framework ◦ Can serve CGI scripts and WSGI applications
  • 9. Tornado Web Overview  Open source version of the framework that powers FriendFeed  Consists of non-blocking web server and web application framework similar to Google’s AppEngine  Includes modules for templating, third- party authorization, localization and a non-blocking http client, among others  Install via easy_install tornado  Runs on Linux, Mac OS X, Windows (support is experimental)
  • 10. Tornado Web Hello, World! import tornado.web import tornado.ioloop class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, Tornado World!") application = tornado.web.Application([ (r"/", MainHandler) ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
  • 11. Asynchronous Tornado Web import tornado.web import tornado.ioloop class AsyncHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://z.com",callback=self.on_resp) def on_resp(self): self.write("Hello, Tornado World!") self.finish()
  • 12. PyMongo and Tornado Web  PyMongo does not provide support for working with asynchronous socket libraries, such as Tornado or Twisted  PyMongo does provide connection pooling, so similar performance benefits may be achieved via multi-threaded code sharing a connection  A driver based on twisted is actively being developed - https://github.com/fiorix/mongo-async- python-driver
  • 13. PyMongo and Tornado Example import tornado.web import tornado.ioloop import pymongo class RestaurantListHandler(tornado.web.RequestHandler): def get(self): db = pymongo.Connection(“localhost”, 27017) venues = db.venues.find() self.render("List.html", venues=venues)
  • 14. Introducing AsycnMongo  AsyncMongo is an asynchronous library for accessing MongoDB  Built on top of Tornado’s ioloop  Released to the community by bit.ly  Current version is 0.1.3 and is stable, but not feature complete (when compared to pymongo)  Relies on PyMongo’s BSON library
  • 15. AsyncMongo and Tornado Example import tornado.web import tornado.ioloop import asyncmongo class RestaurantListHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): db = asyncmongo.Client(host=“192…”, port=27017, …) db.venues.find(limit=10,callback=self.cb) def cb(self, response, error): self.render("List.html", venues=response)
  • 16. Fetching Data with AsyncMongo @tornado.web.asynchronous def get(self): id = self.get_argument("id", None) if id != None: spec = { "_id" : pymongo.objectid.ObjectId(id) } db = DBFactory.create() db.venues.find_one(spec, callback=lambda r, e: self.render(“Edit.html”, venue=r)
  • 17. Inserting Data with AsyncMongo @tornado.web.asynchronous def post(self): doc = {} doc["name"] = self.get_argument("name") doc["city"] = self.get_argument("city") doc["state"] = self.get_argument("state") db = DBFactory.create() db.venues.insert(doc, callback=self._post_callback) def _post_callback(self, response, error): self.write("Created") self.redirect(r"/")
  • 18. Updating Data with AsyncMongo @tornado.web.asynchronous def post(self): id = self.get_argument("_id", None) doc = {} doc["_id"] = pymongo.objectid.ObjectId(id) doc["name"] = self.get_argument("name") doc["city"] = self.get_argument("city") doc["state"] = self.get_argument("state") db = DBFactory.create() db.venues.update({ "_id" : pymongo.objectid.ObjectId(id) }, doc, callback=lambda r, e: self.redirect(r"/"))
  • 19. Deleting Data with AsyncMongo @tornado.web.asynchronous def post(self): id = self.get_argument("_id", None) db = DBFactory.create() db.venues.remove({ "_id" : pymongo.objectid.ObjectId(id) }, callback=lambda r, e: self.redirect(r"/"))
  • 20. Links  http://www.kegel.com/c10k.html  http://www.tornadoweb.org/  https://github.com/facebook/tornado  https://github.com/bitly/asyncmongo  http://www.codevoyeur.com  http://dllhell.net  http://twitter.com/codevoyeur  http://about.me/johnzablocki