Search code examples
pythontornado

Get URL parameter inside prepare() function, instead of get() / post()


I am using tornado and I declared a RequestHandler with a single parameter like this:

class StuffHandler(RequestHandler):
    def get(self, stuff_name):
        ...

app = Application([
    (r'/stuff/(.*)/public', StuffHandler)
])

Now I added another handler for '/stuff/(.*)/private', which requires the user to be authenticated:

class PrivateStuffHandler(RequestHandler):
    @tornado.web.authenticated
    def get(self, stuff_name):
        ...

This of course will cause get_current_user() to be called before get(). The problem is that, in order for get_current_user() to run, I need to know the stuff_name parameter.

So I thought that I may use the prepare() or the initialize() method, which is called before get_current_user(). However, I can't seem to access stuff_name from those methods. I tried putting stuff_name as a parameter but it didn't work, then I tried calling self.get_argument("stuff_name") but it didn't work either.

How do I access an URL parameter from the prepare() method?


Solution

  • In the end, I asked straight to Tornado developers and a helpful user made me notice that there's self.path_args and self.path_kwargs available from anywhere in the class.

    So, from the prepare() method (or even the get_current_user() method), I can do:

    stuff_name = self.path_args[0]