tornado

This is a facebook developed python web interface.

Simple RESTful API in Tornado

Simple Well laid out

from datetime import date
import tornado.escape
import tornado.ioloop
import tornado.web

class VersionHandler(tornado.web.RequestHandler):
    def get(self):
        response = { 'version': '3.5.1',
                     'last_build':  date.today().isoformat() }
        self.write(response)

class GetGameByIdHandler(tornado.web.RequestHandler):
    def get(self, id):
        response = { 'id': int(id),
                     'name': 'Crazy Game',
                     'release_date': date.today().isoformat() }
        self.write(response)

application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
    (r"/version", VersionHandler)
])

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

Please note:

  • 2 Handlers for the Request URLS's
  • 2 Method to handle each one of them
HTTP verb and request URL Tuple (regexp, request_class) that matches the request path RequestHandler subclass and method that is called
GET http://localhost:8888/getgamebyid/500 (r"/getgamebyid/([0-9]+)", GetGameByIdHandler) GetGameByIdHandler.get
GET http://localhost:8888/version (r"/version", VersionHandler) VersionHandler.get

Original Get

This is what the original

GET http://localhost:8888/version

Would look like response headers:

last_build": "2013-08-08", "version": "3.5.1" Date: Thu, 08 Aug 2013 19:45:04 GMT Etag: "d733ae69693feb59f735e29bc6b93770afe1684f" Content-Type: application/json; charset=UTF-8 Server: TornadoServer/3.1 Content-Length: 48

Using the Method

Now the method has been called - we should see output similar to this

Server: TornadoServer/3.1 Content-Type: text/plain Etag: "c305b564aa650a7d5ae34901e278664d2dc81f37" Content-Length: 38 Date: Fri, 09 Aug 2013 02:50:48 GMT

You can see that the content-Type has been altered.

Other Items

If you need to access additional request parameters such as the headers and body data, you can access them through self.request. This variable is a tornado.httpserver.HTTPRequest instance that provides all the information about the HTTP request. The HTTPRequest class is defined in httpserver.py.

Other Interesting things

It appears that we should be able to get access to the body

Content Modifying :)

This looks like what we need

http_response = yield http_client.fetch("http://www.drdobbs.com/web-development")
response = http_response.body.decode().replace(
            "Most Recent Premium Content", "Most Recent Content")
self.write(response)
self.set_header("Content-Type", "text/html")