Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement multiple URL parameters in a Tornado route?

I'm trying to figure out how to implement a URL with up to 3 (optional) url parameters.

I figured out how to do this in ASP.NET MVC 3, but the constraints of the current project eliminated it. So, here's what I'm looking for:

base/{param1}/{param2}/{param3} where param2 and param3 are optional. Is this simply a regex pattern in the handlers section?

like image 931
swasheck Avatar asked Oct 12 '11 18:10

swasheck


1 Answers

I'm not sure if there is a nice way to do it, but this should work:

import tornado.web
import tornado.httpserver

class TestParamsHandler(tornado.web.RequestHandler):
    def get(self, param1, param2, param3):
        param2 = param2 if param2 else 'default2'
        param3 = param3 if param3 else 'default3'
        self.write(
            {
                'param1': param1,
                'param2': param2,
                'param3': param3
            }
        )

# My initial answer is above, but I think the following is better.
class TestParamsHandler2(tornado.web.RequestHandler):
    def get(self, **params):
        self.write(params)


application = tornado.web.Application([
    (r"/test1/(?P<param1>[^\/]+)/?(?P<param2>[^\/]+)?/?(?P<param3>[^\/]+)?", TestParamsHandler),
    (r"/test2/(?P<param1>[^\/]+)/?(?P<param2>[^\/]+)?/?(?P<param3>[^\/]+)?", TestParamsHandler2)
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8080)
tornado.ioloop.IOLoop.instance().start()
like image 196
daharon Avatar answered Oct 13 '22 22:10

daharon