SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
Rapid Web Development with
                    Tornado Web and MongoDB
                                Ikai Lan
                             Twitter: @ikai




Friday, June 10, 2011
About the speaker

                        • Developer Relations at Google
                        • Software Engineering background
                        • Lives in San Francisco, CA
                        • Writes Java, Python on a day to day basis
                        • Twitter: @ikai

Friday, June 10, 2011
This talk

                        • Why Tornado Web and MongoDB?
                        • Whirlwind tour of Tornado (get it?!)
                        • Intro to MongoDB
                        • Brief look at a demo app

Friday, June 10, 2011
What I won’t be talking
                          about

                        • Scalability - loaded topic
                        • Reliability - another loaded topic


Friday, June 10, 2011
So why tornado/
                            mongo?


Friday, June 10, 2011
Joy.
Friday, June 10, 2011
Where does this joy
                          come from?


Friday, June 10, 2011
Freedom.
Friday, June 10, 2011
So really, my talk should
                  have been called “The
                 Joy of Tornado Web and
                        Mongo DB”

Friday, June 10, 2011
Intangibles

                        • Tornado - fast development, very few rules
                        • MongoDB - freedom from a predefined
                          schema
                        • Python, of course. Dynamically typed
                          variables, duck typing plus everything else
                          that is cool about the language



Friday, June 10, 2011
Tornado Web history
                        • Open Sourced by Facebook
                        • ... formerly of FriendFeed
                        • ... former Googlers (that’s why the
                          framework looks like App Engine’s webapp
                          - they wrote it)
                        • Tornado Web powers FriendFeed

Friday, June 10, 2011
A whirlwind tour
Friday, June 10, 2011
Tornado features
                        • Out of the box auth with Twitter,
                          Facebook, Google and FriendFeed
                        • Out of box support for localized strings
                        • Simple templating that allows arbitrary
                          Python code
                        • Asynchronous requests
                        • Small codebase
Friday, June 10, 2011
Simple handlers
                        import tornado.ioloop
                        import tornado.web

                        class HelloHandler(tornado.web.RequestHandler):
                            def get(self):
                                self.write("Hello, world :)")

                        class GoodbyeHandler(tornado.web.RequestHandler):
                            def get(self):
                                self.render("goodbye.html",
                                             message=”Goodbye, world”)

                        application = tornado.web.Application([
                            (r"/hello", HelloHandler),
                            (r"/goodbye", GoodbyeHandler),
                        ])

                        if __name__ == "__main__":
                            application.listen(8888)
                            tornado.ioloop.IOLoop.instance().start()




Friday, June 10, 2011
Asynchronous nature
                  class MainHandler(tornado.web.RequestHandler):

                        @tornado.web.asynchronous
                        def get(self):
                            http = tornado.httpclient.AsyncHTTPClient()
                            http.fetch("http://friendfeed-api.com/v2/feed/bret",
                                       callback=self.on_response)

                        def on_response(self, response):
                            if response.error: raise tornado.web.HTTPError(500)
                            json = tornado.escape.json_decode(response.body)
                            self.write("Fetched " + str(len(json["entries"])) + " entries "
                                       "from the FriendFeed API")
                            self.finish()




Friday, June 10, 2011
Unrestrictive templating
                        {% for student in [p for p in people if p.student and p.age > 23] %}
                          <li>{{ escape(student.name) }}</li>
                        {% end %}



                        # Sample of arbitrary functions in templates
                        def add(x, y):
                           return x + y
                        template.execute(add=add)

                        ### The template
                        {{ add(1, 2) }}




Friday, June 10, 2011
Lies, damn lies and benchmarks




Friday, June 10, 2011
Saving data
Friday, June 10, 2011
MongoDB is an object
                             database

                        • No schema - anything that can be a JSON
                          object can be stored
                        • You can define new collections on the fly


Friday, June 10, 2011
Getting started with
                           Mongo in 4 steps
                        • Download a binary for your system
                        • Create a data directory (mkdir -p /data/db)
                        • Run mongod
                        • Install pymongo
                        • ... start writing code!

Friday, June 10, 2011
Pymongo code sample
              connection = pymongo.Connection()
              database = connection["your_database"]

              def get_or_create_location_by_id(location_id):
                  """
                      Attempts to fetch location data from database. If it doesn't exist,
                      create it. Note that this is NOT concurrency safe.
                  """
                  location_data = database["locations"].find_one({ "_id" : location_id })
                  if location_data is None:
                      location_data = {   "_id" : location_id,
                                          "guards": [],
                                          "owner" : None,
                                          "history" : [],
                                          "last_extort_time" : None
                                       }
                      database.location.save(location_data, safe=True)
                  return location_data




Friday, June 10, 2011
Pymongo queries
              # Add Tyson as a guard to every location owned by “Joe Smith”
              locations = database["locations"].find({ "owner" : "Joe Smith" })
              for location in locations:
                 location["guards"].append("Tyson")
                 database["locations"].save(location)

              # Find everyone who has Tyson as a guard
              locations = database["locations"].find({"guards" : "Tyson"})

              # Find everyone who has *ONLY* Tyson as a guard
              locations = database["locations"].find({"guards" : ["Tyson"]}) # Note []s

              # Find everyone who has Tyson as a guard whose owner is “Ikai Lan”
              locations = database["locations"].find({"guards" : "Tyson",
                                                      "owner" : "Ikai Lan" })




Friday, June 10, 2011
Mold as you go along
Friday, June 10, 2011
Freedom from

                        • ... waiting to get started
                        • ... predefining a schema
                        • ... worrying about complex data structures
                          that don’t fit well into the SQL box.
                          Anything that is JSON can be stored!



Friday, June 10, 2011
More MongoDB
                                 features
                        • Simple Geospatial indexing
                        • GridFS - distributed filesystem running on
                          MongoDB
                        • Out of the box mapreduce
                        • Out of the box replication, data partitioning

Friday, June 10, 2011
Putting it all together
                        • MobSquare, a location based game that
                          uses the Facebook API.
                        • Mashup: Mafia Wars + FourSquare
                        • https://github.com/ikai/mobsquare-demo
                        • “Check in” to locations, take them over,
                          extort money and fight other gangs


Friday, June 10, 2011
Why are Tornado/
                             Mongo a fit?
                        • If I haven’t said it enough yet, they’re fun
                        • Facebook API performance varies -
                          asynchronous so we can serve requests
                          while waiting
                        • Highly structured player data

Friday, June 10, 2011
OAuth 2 upgrade flow
                        class OnLoginHandler(tornado.web.RequestHandler):

                            @tornado.web.asynchronous
                            def get(self):
                                # Store this somewhere
                                code = self.get_argument("code")
                                access_token_url = ACCESS_TOKEN_URL_TPL + code
                                client = httpclient.AsyncHTTPClient()
                                client.fetch(access_token_url, self.on_fetched_token)

                            def on_fetched_token(self, response):
                                """ Callback inokved when the auth_token is fetched """
                                matches = ACCESS_TOKEN_REGEX.search(response.body)
                                if matches:
                                    access_token = matches.group(1)
                                    client = httpclient.AsyncHTTPClient()
                                    # lambda is effectively a function factory for us
                                    client.fetch(API["profile"] % access_token,
                                        lambda response: self.on_profile_fetch(response, access_token))

                            def on_profile_fetch(self, response, access_token):
                                """ Callback invoked when we have fetched the user's profile """
                                profile = json.loads(response.body)
                                profile["access_token"] = access_token
                                profile_id = db.save_profile(profile)
                                self.set_secure_cookie("user_id", str(profile_id))
                                self.redirect("/") # implictly calls self.finish()



Friday, June 10, 2011
Known gotchas

                        • Immaturity of frameworks, tools
                        • Tornado templating errors result in
                          somewhat useless stack traces
                        • MongoDB nuances
                        • Tornado community fairly small

Friday, June 10, 2011
Questions?

                        • Ikai Lan - @ikai on Twitter
                        • Github: https://github.com/ikai
                        • Google Profile: https://profiles.google.com/
                          ikai.lan/about
                        • Thank you for having me at Pycon!

Friday, June 10, 2011
Attributions

                        •   Slide 6: Kirstin Jennings - “big smile!” http://www.flickr.com/photos/methyl_lives/2973265796/

                        •   Slide 8: Tony Blay - “I am a bird now!” http://www.flickr.com/photos/toniblay/59415205/

                        •   Slide 12: Antonio Sofi - “whirlwind” http://www.flickr.com/photos/webgol/36546734

                        •   Slide 17: Tornado Web documentation - http://www.tornadoweb.org/documentation

                        •   Slide 18: Christine of Robot Brainz - “Cassette” http://www.flickr.com/photos/robotbrainz/
                            2786347158/

                        •   Slide 23: Samuel Stroube - “Play-Doh on a Picnic Table” http://www.flickr.com/photos/samoube/
                            203586664




Friday, June 10, 2011

Contenu connexe

Tendances

Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014nvpuppet
 
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
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
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
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterSimen Li
 

Tendances (20)

Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014
 
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
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Event loop
Event loopEvent loop
Event loop
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
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
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Node.js
Node.jsNode.js
Node.js
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 

En vedette

An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Real time server
Real time serverReal time server
Real time serverthepian
 
Programmation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoProgrammation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoRonan Amicel
 
Introduction to Tornado - TienNA
Introduction to Tornado - TienNAIntroduction to Tornado - TienNA
Introduction to Tornado - TienNAFramgia Vietnam
 
Contoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta GuruContoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta Guruenesha sie
 

En vedette (7)

An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Real time server
Real time serverReal time server
Real time server
 
Programmation web asynchrone avec Tornado
Programmation web asynchrone avec TornadoProgrammation web asynchrone avec Tornado
Programmation web asynchrone avec Tornado
 
Tornado
TornadoTornado
Tornado
 
Tornado
TornadoTornado
Tornado
 
Introduction to Tornado - TienNA
Introduction to Tornado - TienNAIntroduction to Tornado - TienNA
Introduction to Tornado - TienNA
 
Contoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta GuruContoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta Guru
 

Similaire à Rapid web development using tornado web and mongodb

Pycon2011 android programming-using_python
Pycon2011 android programming-using_pythonPycon2011 android programming-using_python
Pycon2011 android programming-using_pythonGeorge Goh
 
Large problems, Mostly Solved
Large problems, Mostly SolvedLarge problems, Mostly Solved
Large problems, Mostly Solvedericholscher
 
Mongo db with spring data document
Mongo db with spring data documentMongo db with spring data document
Mongo db with spring data documentSean Lee
 
IPTC News in JSON Spring 2013
IPTC News in JSON Spring 2013IPTC News in JSON Spring 2013
IPTC News in JSON Spring 2013Stuart Myles
 
So, you think you know widgets.
So, you think you know widgets.So, you think you know widgets.
So, you think you know widgets.danielericlee
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.WO Community
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo ToolkitThomas Koch
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHPConFoo
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기형우 안
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPsmueller_sandsmedia
 
SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersElena-Oana Tabaranu
 
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
 
Getting Started with Wonder
Getting Started with WonderGetting Started with Wonder
Getting Started with WonderWO Community
 
Plone - A History of Python Web
Plone - A History of Python WebPlone - A History of Python Web
Plone - A History of Python WebAlexander Loechel
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Julie Lerman
 

Similaire à Rapid web development using tornado web and mongodb (20)

Pycon2011 android programming-using_python
Pycon2011 android programming-using_pythonPycon2011 android programming-using_python
Pycon2011 android programming-using_python
 
Large problems, Mostly Solved
Large problems, Mostly SolvedLarge problems, Mostly Solved
Large problems, Mostly Solved
 
Mongo db with spring data document
Mongo db with spring data documentMongo db with spring data document
Mongo db with spring data document
 
IPTC News in JSON Spring 2013
IPTC News in JSON Spring 2013IPTC News in JSON Spring 2013
IPTC News in JSON Spring 2013
 
So, you think you know widgets.
So, you think you know widgets.So, you think you know widgets.
So, you think you know widgets.
 
Railsconf 2010
Railsconf 2010Railsconf 2010
Railsconf 2010
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDB
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo Toolkit
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHP
 
What is Python?
What is Python?What is Python?
What is Python?
 
Yahoo is open to developers
Yahoo is open to developersYahoo is open to developers
Yahoo is open to developers
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
SXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBustersSXSW 2012 JavaScript MythBusters
SXSW 2012 JavaScript MythBusters
 
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)
 
Getting Started with Wonder
Getting Started with WonderGetting Started with Wonder
Getting Started with Wonder
 
App Engine Meetup
App Engine MeetupApp Engine Meetup
App Engine Meetup
 
Plone - A History of Python Web
Plone - A History of Python WebPlone - A History of Python Web
Plone - A History of Python Web
 
Entity Framework Today (May 2012)
Entity Framework Today (May 2012)Entity Framework Today (May 2012)
Entity Framework Today (May 2012)
 

Plus de ikailan

Your language doesn't scale
Your language doesn't scaleYour language doesn't scale
Your language doesn't scaleikailan
 
From 0-1 billion in 46 days
From 0-1 billion in 46 daysFrom 0-1 billion in 46 days
From 0-1 billion in 46 daysikailan
 
2011 august-gdd-mexico-city-rest-json-oauth
2011 august-gdd-mexico-city-rest-json-oauth2011 august-gdd-mexico-city-rest-json-oauth
2011 august-gdd-mexico-city-rest-json-oauthikailan
 
2011 aug-gdd-mexico-city-high-replication-datastore
2011 aug-gdd-mexico-city-high-replication-datastore2011 aug-gdd-mexico-city-high-replication-datastore
2011 aug-gdd-mexico-city-high-replication-datastoreikailan
 
2011 july-nyc-gtug-go
2011 july-nyc-gtug-go2011 july-nyc-gtug-go
2011 july-nyc-gtug-goikailan
 
2011 july-gtug-high-replication-datastore
2011 july-gtug-high-replication-datastore2011 july-gtug-high-replication-datastore
2011 july-gtug-high-replication-datastoreikailan
 
Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011ikailan
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathonikailan
 
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Goikailan
 
Introducing the App Engine datastore
Introducing the App Engine datastoreIntroducing the App Engine datastore
Introducing the App Engine datastoreikailan
 
What is App Engine? O
What is App Engine? OWhat is App Engine? O
What is App Engine? Oikailan
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010ikailan
 
Boot camp 2010_app_engine_101
Boot camp 2010_app_engine_101Boot camp 2010_app_engine_101
Boot camp 2010_app_engine_101ikailan
 
Building TweetEngine
Building TweetEngineBuilding TweetEngine
Building TweetEngineikailan
 

Plus de ikailan (14)

Your language doesn't scale
Your language doesn't scaleYour language doesn't scale
Your language doesn't scale
 
From 0-1 billion in 46 days
From 0-1 billion in 46 daysFrom 0-1 billion in 46 days
From 0-1 billion in 46 days
 
2011 august-gdd-mexico-city-rest-json-oauth
2011 august-gdd-mexico-city-rest-json-oauth2011 august-gdd-mexico-city-rest-json-oauth
2011 august-gdd-mexico-city-rest-json-oauth
 
2011 aug-gdd-mexico-city-high-replication-datastore
2011 aug-gdd-mexico-city-high-replication-datastore2011 aug-gdd-mexico-city-high-replication-datastore
2011 aug-gdd-mexico-city-high-replication-datastore
 
2011 july-nyc-gtug-go
2011 july-nyc-gtug-go2011 july-nyc-gtug-go
2011 july-nyc-gtug-go
 
2011 july-gtug-high-replication-datastore
2011 july-gtug-high-replication-datastore2011 july-gtug-high-replication-datastore
2011 july-gtug-high-replication-datastore
 
Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011Intro to App Engine - Agency Dev Day NYC 2011
Intro to App Engine - Agency Dev Day NYC 2011
 
2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon2011 june-kuala-lumpur-gtug-hackathon
2011 june-kuala-lumpur-gtug-hackathon
 
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
2011 June - Singapore GTUG presentation. App Engine program update + intro to Go
 
Introducing the App Engine datastore
Introducing the App Engine datastoreIntroducing the App Engine datastore
Introducing the App Engine datastore
 
What is App Engine? O
What is App Engine? OWhat is App Engine? O
What is App Engine? O
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010
 
Boot camp 2010_app_engine_101
Boot camp 2010_app_engine_101Boot camp 2010_app_engine_101
Boot camp 2010_app_engine_101
 
Building TweetEngine
Building TweetEngineBuilding TweetEngine
Building TweetEngine
 

Dernier

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
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
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
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
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
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
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Rapid web development using tornado web and mongodb

  • 1. Rapid Web Development with Tornado Web and MongoDB Ikai Lan Twitter: @ikai Friday, June 10, 2011
  • 2. About the speaker • Developer Relations at Google • Software Engineering background • Lives in San Francisco, CA • Writes Java, Python on a day to day basis • Twitter: @ikai Friday, June 10, 2011
  • 3. This talk • Why Tornado Web and MongoDB? • Whirlwind tour of Tornado (get it?!) • Intro to MongoDB • Brief look at a demo app Friday, June 10, 2011
  • 4. What I won’t be talking about • Scalability - loaded topic • Reliability - another loaded topic Friday, June 10, 2011
  • 5. So why tornado/ mongo? Friday, June 10, 2011
  • 7. Where does this joy come from? Friday, June 10, 2011
  • 9. So really, my talk should have been called “The Joy of Tornado Web and Mongo DB” Friday, June 10, 2011
  • 10. Intangibles • Tornado - fast development, very few rules • MongoDB - freedom from a predefined schema • Python, of course. Dynamically typed variables, duck typing plus everything else that is cool about the language Friday, June 10, 2011
  • 11. Tornado Web history • Open Sourced by Facebook • ... formerly of FriendFeed • ... former Googlers (that’s why the framework looks like App Engine’s webapp - they wrote it) • Tornado Web powers FriendFeed Friday, June 10, 2011
  • 12. A whirlwind tour Friday, June 10, 2011
  • 13. Tornado features • Out of the box auth with Twitter, Facebook, Google and FriendFeed • Out of box support for localized strings • Simple templating that allows arbitrary Python code • Asynchronous requests • Small codebase Friday, June 10, 2011
  • 14. Simple handlers import tornado.ioloop import tornado.web class HelloHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world :)") class GoodbyeHandler(tornado.web.RequestHandler): def get(self): self.render("goodbye.html", message=”Goodbye, world”) application = tornado.web.Application([ (r"/hello", HelloHandler), (r"/goodbye", GoodbyeHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() Friday, June 10, 2011
  • 15. Asynchronous nature class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://friendfeed-api.com/v2/feed/bret", callback=self.on_response) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " entries " "from the FriendFeed API") self.finish() Friday, June 10, 2011
  • 16. Unrestrictive templating {% for student in [p for p in people if p.student and p.age > 23] %} <li>{{ escape(student.name) }}</li> {% end %} # Sample of arbitrary functions in templates def add(x, y): return x + y template.execute(add=add) ### The template {{ add(1, 2) }} Friday, June 10, 2011
  • 17. Lies, damn lies and benchmarks Friday, June 10, 2011
  • 19. MongoDB is an object database • No schema - anything that can be a JSON object can be stored • You can define new collections on the fly Friday, June 10, 2011
  • 20. Getting started with Mongo in 4 steps • Download a binary for your system • Create a data directory (mkdir -p /data/db) • Run mongod • Install pymongo • ... start writing code! Friday, June 10, 2011
  • 21. Pymongo code sample connection = pymongo.Connection() database = connection["your_database"] def get_or_create_location_by_id(location_id): """ Attempts to fetch location data from database. If it doesn't exist, create it. Note that this is NOT concurrency safe. """ location_data = database["locations"].find_one({ "_id" : location_id }) if location_data is None: location_data = { "_id" : location_id, "guards": [], "owner" : None, "history" : [], "last_extort_time" : None } database.location.save(location_data, safe=True) return location_data Friday, June 10, 2011
  • 22. Pymongo queries # Add Tyson as a guard to every location owned by “Joe Smith” locations = database["locations"].find({ "owner" : "Joe Smith" }) for location in locations: location["guards"].append("Tyson") database["locations"].save(location) # Find everyone who has Tyson as a guard locations = database["locations"].find({"guards" : "Tyson"}) # Find everyone who has *ONLY* Tyson as a guard locations = database["locations"].find({"guards" : ["Tyson"]}) # Note []s # Find everyone who has Tyson as a guard whose owner is “Ikai Lan” locations = database["locations"].find({"guards" : "Tyson", "owner" : "Ikai Lan" }) Friday, June 10, 2011
  • 23. Mold as you go along Friday, June 10, 2011
  • 24. Freedom from • ... waiting to get started • ... predefining a schema • ... worrying about complex data structures that don’t fit well into the SQL box. Anything that is JSON can be stored! Friday, June 10, 2011
  • 25. More MongoDB features • Simple Geospatial indexing • GridFS - distributed filesystem running on MongoDB • Out of the box mapreduce • Out of the box replication, data partitioning Friday, June 10, 2011
  • 26. Putting it all together • MobSquare, a location based game that uses the Facebook API. • Mashup: Mafia Wars + FourSquare • https://github.com/ikai/mobsquare-demo • “Check in” to locations, take them over, extort money and fight other gangs Friday, June 10, 2011
  • 27. Why are Tornado/ Mongo a fit? • If I haven’t said it enough yet, they’re fun • Facebook API performance varies - asynchronous so we can serve requests while waiting • Highly structured player data Friday, June 10, 2011
  • 28. OAuth 2 upgrade flow class OnLoginHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): # Store this somewhere code = self.get_argument("code") access_token_url = ACCESS_TOKEN_URL_TPL + code client = httpclient.AsyncHTTPClient() client.fetch(access_token_url, self.on_fetched_token) def on_fetched_token(self, response): """ Callback inokved when the auth_token is fetched """ matches = ACCESS_TOKEN_REGEX.search(response.body) if matches: access_token = matches.group(1) client = httpclient.AsyncHTTPClient() # lambda is effectively a function factory for us client.fetch(API["profile"] % access_token, lambda response: self.on_profile_fetch(response, access_token)) def on_profile_fetch(self, response, access_token): """ Callback invoked when we have fetched the user's profile """ profile = json.loads(response.body) profile["access_token"] = access_token profile_id = db.save_profile(profile) self.set_secure_cookie("user_id", str(profile_id)) self.redirect("/") # implictly calls self.finish() Friday, June 10, 2011
  • 29. Known gotchas • Immaturity of frameworks, tools • Tornado templating errors result in somewhat useless stack traces • MongoDB nuances • Tornado community fairly small Friday, June 10, 2011
  • 30. Questions? • Ikai Lan - @ikai on Twitter • Github: https://github.com/ikai • Google Profile: https://profiles.google.com/ ikai.lan/about • Thank you for having me at Pycon! Friday, June 10, 2011
  • 31. Attributions • Slide 6: Kirstin Jennings - “big smile!” http://www.flickr.com/photos/methyl_lives/2973265796/ • Slide 8: Tony Blay - “I am a bird now!” http://www.flickr.com/photos/toniblay/59415205/ • Slide 12: Antonio Sofi - “whirlwind” http://www.flickr.com/photos/webgol/36546734 • Slide 17: Tornado Web documentation - http://www.tornadoweb.org/documentation • Slide 18: Christine of Robot Brainz - “Cassette” http://www.flickr.com/photos/robotbrainz/ 2786347158/ • Slide 23: Samuel Stroube - “Play-Doh on a Picnic Table” http://www.flickr.com/photos/samoube/ 203586664 Friday, June 10, 2011