Python Tornado get URL arguments

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"}

As Gennady Kandaurov mentioned, you passed the key as a part of the we.URLSpec path and you can access it using Tornado's self.path_kwargs. If you wanted to pass it as an argument you could used RequestHandler.get_argument to get the argument on your get method and use self.request.arguments on your prepare method to access it as your initial intention.

Your code could be as follow:

class Application(tornado.web.Application):
    def __init__(self):
        user_route = r"/users"
        app = tornado.web.Application([
            tornado.web.url(user_route, user_manager.UserHandler), ..])

class UserHandler(tornado.web.RequestHandler):
    def get(self):
        key = self.get_argument('key')
        print(key)

    def prepare(self):
        # inspect request arguments
        print(self.request.arguments)

Please let me know if you have any further question.


It's generally bad to use a character like = in a URL path fragment, since they are generally used for query arguments. Either don't use it:

`r"/users/(?P<key>\w+)"`

or turn it into a proper query argument

`r"/users/\?key=(?P<key>\w+)"`

Otherwise it's confusing for a maintainer to try to figure out which scheme you intended to use (did you really want to route a path fragment called /key%3D\w+? Or did you really mean you wanted a query arg and forgot the ??)

In any case, for URL path fragment matching ("slug-matching"), using argument unpacking can let you access them in the handler too, without having to invoke path_kwargs:

# `r"/users/(?P<key>\w+)"`
class Handler(RequestHandler):
    def get(self, **kwargs):
        key = kwargs.get('key')
        # I prefer dict.get() here, since if you change the `+` to a `*`,
        # it's possible that no key was supplied, and kwargs['key']
        # will throw a KeyError exception

If you intended to use a query argument for key, then @afxentios's answer is appropriate. (You can also use self.get_query_argument('key') which will explicitly only look for query arguments in the URL (whereas get_argument also checks in the request BODY for a www-url-encoded argument (such as if you POST)).

Tags:

Python

Tornado