How can I implement multiple URL parameters in a T

2019-03-10 01:16发布

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?

1条回答
我命由我不由天
2楼-- · 2019-03-10 01:57

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()
查看更多
登录 后发表回答