Search code examples
pythonjsonptornadopython-2.6

JSONp requests with tornado


I am wondering how best to handle JSONp objects using tornado in python, is it best to do this:

class BaseRequest(tornado.web.RequestHandler):
      def prepare(self):
          self.result = {"success": True};
      def finish(self, chunk=None):
          self.write(self.result);
          tornado.web.RequestHandler.finish(self, chunk);

This seems like a bad idea because you'd think you could do it in on_finish(), right?

So, should I do it like above or should I write() in each of my handlers?


Solution

  • You should override the default write method and do something like this (untested):

    class YourHandler(tornado.web.RequestHandler):
        ...
        def write(self, stuff):
            super(YourHandler, self).write('callback(' + json.dumps(stuff) + ')')
            self.set_header('Content-Type', 'application/javascript')
    

    where stuff is a dictionary and callback is the jsonp callback name.