本文地址:http://blog.csdn.net/spch2008/article/details/9005140
当路由条目过多时,需要一条一条注册,过于麻烦,此时可以通过resource route简化
map.connect("messages", "/messages", controller="messages", action="create", conditions=dict(method=["POST"])) map.connect("messages", "/messages", controller="messages", action="index", conditions=dict(method=["GET"])) map.connect("formatted_messages", "/messages.{format}", controller="messages", action="index", conditions=dict(method=["GET"])) map.connect("new_message", "/messages/new", controller="messages", action="new", conditions=dict(method=["GET"])) map.connect("formatted_new_message", "/messages/new.{format}", controller="messages", action="new", conditions=dict(method=["GET"])) map.connect("/messages/{id}", controller="messages", action="update", conditions=dict(method=["PUT"])) map.connect("/messages/{id}", controller="messages", action="delete", conditions=dict(method=["DELETE"])) map.connect("edit_message", "/messages/{id}/edit", controller="messages", action="edit", conditions=dict(method=["GET"])) map.connect("formatted_edit_message", "/messages/{id}.{format}/edit", controller="messages", action="edit", conditions=dict(method=["GET"])) map.connect("message", "/messages/{id}", controller="messages", action="show", conditions=dict(method=["GET"])) map.connect("formatted_message", "/messages/{id}.{format}", controller="messages", action="show", conditions=dict(method=["GET"]))
map.resource("message", "messages")两个参数,一个指定单数,为member路由名字;一个指定复数,为collection路由名字。
函数原型:resource(member_name, collection_name, **kwargs)
GET /messages => messages.index() => url("messages") POST /messages => messages.create() => url("messages") GET /messages/new => messages.new() => url("new_message") PUT /messages/1 => messages.update(id) => url("message", id=1) DELETE /messages/1 => messages.delete(id) => url("message", id=1) GET /messages/1 => messages.show(id) => url("message", id=1) GET /messages/1/edit => messages.edit(id) => url("edit_message", id=1)
这里有必要说一下member 路由与 collection路由。
上述的路由模型
GET /messages => messages.index() POST /messages => messages.create() GET /messages/new => messages.new() PUT /messages/1 => messages.update(id) DELETE /messages/1 => messages.delete(id) GET /messages/1 => messages.show(id) GET /messages/1/edit => messages.edit(id)
一个member路由指定具体实例,也就是说它们有id。而一个collection路由,
没有指定的实例,即没有给定id
综上:member路由操作一个单独的实例,而collection操作全体实例。
另一个函数collection也可以完成上述功能。
函数原型:collection(collection_name, resource_name, path_prefix=None, member_prefix='/{id}', controller=None, collection_actions=['index', 'create', 'new'],member_actions=['show', 'update', 'delete', 'edit'], member_options=None, **kwargs)
用法:
map.collection('entries', 'entry')