Tornado Restful Handler Classes

一个人想着一个人 提交于 2019-11-29 23:19:06

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!