newbie
newbie

Reputation: 1515

Python Tornado Request Handler Mapping

I'm just getting started with Tornado and I was wondering how i can define a mapping so that all requests like below are are handled by a single handler.

  1. /products/list
  2. /products/find/123
  3. /products/copy/123
  4. /products/{action}/{argument1}/{argument2}/{argument3}

    class Application(tornado.web.Application):
        def __init__(self):
            handlers = [
                (r"/", home.HomeHandler),
                (r"/products/", product.ProductHandler)]
    
    class ProductHandler(base.BaseHandler):   
      def get(self, action, *args):
              self.write("Action:" + action + "<br>")
                    for arg in args:
                        self.write("argument:" + arg + "<br>")
    

Upvotes: 0

Views: 1934

Answers (1)

jeffknupp
jeffknupp

Reputation: 6314

You aren't limited to listing a RequestHandler just once in the url matching, so you can do one of two things: Add a pattern explicitly matching each of the patterns you mention above like so:

def __init__(self):
    handlers = [
        (r"/", home.HomeHandler),
        (r"/products/list/([0-9]+)", product.ProductHandler)
        (r"/products/find/([0-9]+)", product.ProductHandler)
        (r"/products/copy/([0-9]+)", product.ProductHandler)
        (r"/products/(\w+)/(\w+)/(\w+)", product.ProductHandler)]

Or you could say that "any URL that begins with "products" should be sent to the product handler," like so:

def __init__(self):
    handlers = [
        (r"/", home.HomeHandler),
        (r"/products/list/(.*)", product.ProductHandler)

and parse the variable list yourself in the ProductHandler.

Upvotes: 1

Related Questions