Search code examples
pythonparsingrouteshttprequesttornado

How do I get access to parts of my url/path in a tornado request handler


Sorry if this question seems basic, but I don't know how to google for what I want, so some explanation is required.

I am using tornado for my server/routing. Here is what I am attempting to do.

http = tornado.web.Application([
    (r"/myroute/*", request_handlers.MyHandler, {}),
    (r"/",  request_handlers.defaultHandler, {}),
], **settings)
http.listen(port)

So to explain this, whenever a route beginning with "/myroute/" is called, whatever is immediately after the 2nd slash will be interpreted as the required 2nd portion of the path. This value can be empty string.

Some example of paths that I would need to be able to parse...

"/myroute/?var1=foo&var2=bar"    ## the required portion is empty string
"/myroute/something?var1=foo"     ## the required portion is "something"
"/myroute/something"             ## same, without options

Now in my request handler, I am able to access my options pretty easily.

class MyHandler(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        var1 = self.get_argument('var1')
        print var1       ## 'foo'
        var2 = self.get_argument('var2')
        print var2       ## 'bar'

Basically, several questions.

1) However, how would I also access the "something" portion of the path, if we are sticking with my example?

2) Is there better terminology for what I am looking for? I have no doubt this is googleable if I only knew what to search for.


Solution

  • Tornado gives you access to the path with self.request.path. You can then split it up into the path components.

    Let's say your path is /myroute/something.

    class MyHandler(tornado.web.RequestHandler):
        def get(self, *args, **kwargs):
            components = [x for x in self.request.path.split("/") if x]
            # results in ['myroute', 'something']