Search code examples
pythontornado

How to set the tornado routing for handler with init parameters?


I'm building a tornado web server. One of the handler requires init parameters. How to set the routing list so I can pass the values for the paramters?

class ActionHandler():
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

    async def post(self, action):
        x = self.p1 
        y = self.p2
        # ....

app = tornado.web.Application([
    ('/action', ActionHandler) # How to pass init parameters?

Solution

  • The documentation notes that you should not override the __init__ method of a RequestHandler subclass. If you want to pass initial arguments to the handler, use the initialze method.

    class ActionHandler():
        def initialze(self, p1, p2):
            self.p1 = p1
            self.p2 = p2
    
    # then pass these arguments in a dict 
    # when you register the route
    app = tornado.web.Application([
        ('/action', ActionHandler, {'p1': 'Hello', 'p2': 'World'}),
    ])