Tornado Restful Handler Classes

odgrim picture odgrim · Nov 18, 2011 · Viewed 7.6k times · Source

I've read around and found this answered question about a problem relating to this but what I really want to know is how to implement this structure and how many handler classes I need:

1  GET    /items        #=> index
2  GET    /items/1      #=> show
3  GET    /items/new    #=> new
4  GET    /items/1/edit #=> edit
5  PUT    /items/1      #=> update
6  POST   /items        #=> create
7  DELETE /items/1      #=> destroy

I was thinking having 2,5,7 mapped to a single handler routed to /items/[0-9]+ and having 3 new handlers for the items, items/new and /items/[0-9]+/edit. The downside is that it felt like a sub-optimal solution to have 4 handlers for a single resource.

I'm terribly new to proper routing/handling/webapps but I at least give it a good read before I start on something. Are there any better suggestions for how many/how you route your handlers?

Answer

aychedee picture aychedee · Sep 12, 2012

Well, it is largely stylistic. Each request handler in this situation represents the removal of an if statement from one of your methods. I think it can be clearer to limit the number of RequestHandlers. The clearest results I think can be achieved with one handler and three routes.

I've also thrown away your item 3. Because it is a duplication of item 6. If having an 'items/new' url is really important then we could put it back in. Though I think at that point you would need another handler class for clarity.

class ItemHandler(tornado.web.RequestHandler):

    def get(self, item_id=None, edit=False):
        if item_id:
            # get item from db
            if edit:
                new_data_from_query_string = self.get_argument('item_data')
                # do edit, save item
            # return item
        else:
            # return index

    def put(self, item_id):
        data = self.get_argument('item_data')
        # do your update for item

    def post(self):
        data = self.get_argument('item_data')
        # do your item creation

    def delete(self, item_id):
        # do your deletion for item_id

Then the actual application could be created like this:

tornado.web.application([
    (r'/items$', ItemHandler),
    (r'/items/(\d+$)', ItemHandler),
    (r'/items/(\d+)/(edit)$', ItemHandler),
])

If you want the '/items/new' url then I would probably suggest putting that in a separate handler because it would otherwise make the logic overly complex.