tornado

how to handle multiple routes in the same class with tornado web server


I am writting a very simple web application with tornado:

class MainHandler1(tornado.web.RequestHandler):
  def get(self):
     self.render("page1.html")

class MainHandler2(tornado.web.RequestHandler):
  def get(self):
     self.render("page2.html")
...

application = tornado.web.Application([(r'/route1', MainHandler1), (r'/route2', MainHandler2)], **settings)

As you can see i have 2 routes, and i need to create 2 classes for those routes. Is there a way to manage several routes with the same class ?

Thanks


Solution

  • Yes, just use the same class in your route specs:

    routes = [
        (r'/route1', MainHandler1),
        (r'/route2', MainHandler1)
    ]
    application = tornado.web.Application(routes, **settings)
    

    EDIT re "how will I differentiate route1 and route2 in MainHandler1":

    I would suggest you not to tie your handler to any explicit routes; instead try to parametrise it based on variable parts of the route. If we take your original example, where you have two routes differing by a number and serving a different template based on that number, you might have something like:

    class MainHandler(tornado.web.RequestHandler):
        def get(self, page_num):
            self.render("page{}.html".format(page_num))
    
    routes = [
        (r'/route(\d+)', MainHandler),
    ]
    application = tornado.web.Application(routes, **settings)
    

    This way you define one route, but effectively have as many as you have templates. On the other hand, if you need a completely different response for each route, it's much better to keep them in separate handlers.