Search code examples
pythontornado

Python Tornado get URL arguments


I'm trying to inspect a request's argument before the get() is invoked. I have a route which is described as so:

user_route = r"/users/key=(?P<key>\w+)"
app = web.Application([
        web.URLSpec(user_route, user_manager.UserHandler), ..])

Next, (in the handler) prepare() is used to inspect the request before get().

def prepare(self):
    # inspect request arguments
    print(self.request.arguments) # prints "{}"

The problem I'm having is that I cannot access the arguments from prepare(). The last statement prints an empty dict. My get() successfully uses the arguments as they are passed in the function like this:

def get(self, key):
      print(key) #works

How do I access arguments in prepare()? I have also tried self.argument('key') which gives an error "400 GET .... Missing argument key", but requested URL does have a key argument in it.


Solution

  • In your code key is not a GET-argument, it's a part of a path. tornado.we.URLSpec passes any capturing groups in the regex into the handler’s get/post/etc methods as arguments.

    tornado.web.RequestHandler has RequestHandler.path_args and RequestHandler.path_kwargs which contain the positional and keyword arguments from URLSpec. Those are available in prepare method:

    def prepare(self):
        # inspect request arguments
        print(self.path_kwargs) # prints {"key": "something"}