Search code examples
pythonpython-2.7routestornado

How to map a route to a function in Tornado?


I want to set more than one get route in a class. Or simply map a route to a function.

This is what I've done:

class TestRoute1(tornado.web.RequestHandler):
    def get(self):
        self.write("I have done something.")

class TestRoute2(tornado.web.RequestHandler):
    def get(self):
        self.write("This is something else.")

application = tornado.web.Application([
    (r"/test1", TestRoute1),
    (r"/test2", TestRoute2),
])
application.listen(8080)

And this is what I think should be possible to do:

class TestRoute(tornado.web.RequestHandler):
    def func1(self):
        self.write("I have done something.")

    def func2(self):
        self.write("This is something else.")

application = tornado.web.Application([
    (r"/test1", TestRoute.func1),
    (r"/test2", TestRoute.func2),
])
application.listen(8080)

Or something like this. Is it possible? If it is not, what is the alternatives to one I use?


Solution

  • In general, the idiomatic way to do this in Tornado is to use two separate classes as you've done in your first example, and use a common base class to contain any code that needs to be shared between them.

    There are, however, two ways to pass additional information from the routing table into the handler. First, if there are capturing groups in the routing regex, the substrings they capture will be passed to the get/post/etc methods. Second, you may pass an additional dictionary in the routing table (as a third element of the tuple); this dictionary will become keyword arguments to the handler's initialize() method.