1

I'm using tornado, and have a bunch of handlers that map to different urls. For example :

#mainfile.py

#imports
#...
application = tornado.web.Application([
    (r"/", DefaultHandler),
    (r"/somepath", SomepathHandler),
], debug=True)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    port = int(os.environ.get("PORT", 8001))
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()

Now, in DefaultHandler and SomepathHandler, I don't like the way error messages are displayed, so I decided to overwrite the write_error method like this :

#DefaultHandler.py
class DefaultHandler(tornado.web.RequestHandler):

    def write_error(self, status_code, **kwargs):
        self.write("a nicer message")

    def initialize(self):
        #stuff
    def get(self):
        #more stuff, etc.

And then

#Somepathhandler.py
class SomepathHandler(tornado.web.RequestHandler):
    def write_error(self, status_code, **kwargs):
        self.write("a nicer message")

And this will surely continue with other handlers. I read the Tornado docs, and it seems like I should be subclassing class tornado.web.RequestHandler(application, request, **kwargs), but have not managed to do so successfully. I'm not quite sure where the class should go, and how can I make it register with my application?

thanks!

L-R
  • 1,214
  • 1
  • 19
  • 40

1 Answers1

1

You're nearly there. As you said, you just need to subclass RequestHandler. The class can go in any file, as long as you import it where it's required.

class BaseHandler(tornado.web.RequestHandler):

    def write_error(self, status_code, **kwargs):
        self.write("a nicer message")

class DefaultHandler(BaseHandler):

    def initialize(self):
        pass

    def get(self):
        pass

class SomepathHandler(BaseHandler):
    pass
Cole Maclean
  • 5,627
  • 25
  • 37