Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tornado get URL arguments

Tags:

python

tornado

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.

like image 569
theQuestions Avatar asked Dec 14 '16 17:12

theQuestions


2 Answers

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"}
like image 152
Gennady Kandaurov Avatar answered Sep 24 '22 22:09

Gennady Kandaurov


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.

like image 21
afxentios Avatar answered Sep 22 '22 22:09

afxentios