在stack overflow上看到的关于tornado-RESTful的讨论


一段帖子里面的讨论,对我这样的新手收益良多

Question:

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:

Well, it is largely stylistic. Each request handler in this situationrepresents the removal of an if statement from one of your methods. I think it can be clearer to limit the number of RequestHandlers. The clearestresults 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. Ifhaving 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 ina separate handler because it would otherwise make the logic overly complex.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值