我正在使用RESTlet为一组相关的资源设计一个RESTful应用程序接口。
例如:
人员(/people/124)资源具有属性"favoriteThing“,该属性可以是汽车、食品、玩具。
现在假设API的用户想要通过向/person/124/favoriteThing URL执行POST来更新此属性。
但是,为了处理这个请求,我需要在数据存储中记录这个新关系(需要一个键(Kind,Id))。
所以我有两个麻烦的选择:
1)希望在帖子的正文中有一个URL (这似乎是RESETful),但是我如何才能干净利落地将URL转换为Datastore Key,requires (Kind,ID)。
2)在POST的主体中期望(Kind,ID) (非常简单),但这允许URL以外的其他内容作为API中的资源标识符
对此问题最具RESTful的解决方案是什么?也许是我考虑过的以外的事情。
发布于 2011-11-01 22:37:54
(我在这里假设使用Python,因为它更简洁)
将'thing‘本身作为POST参数发布到/person/124/favoriteThing对我来说似乎是正确的。
所以现在你的问题是,如何干净利落地实现它?那么,URI中的“124”是否是Person的键?你可以通过强制转换将Key()编码成一个字符串,例如。
uri = '/person/%s' % str(person.key())
一个很好的技巧是可以在WSGIApplication构造函数中使用正则表达式分组:
def main():
application = WSGIApplication(['/people/(.*)', PersonHandler], debug=True)
然后,当你在你的PersonHandler上发布帖子时,你可以拆分相关的路径:
class PersonHandler(RequestHandler):
def post(self, path):
(key, property) = path.split('/')
person = Person().get(Key(key))
# check that property is valid, get POST param and change it
发布于 2011-11-01 23:22:39
要扩展Moishe的响应,实际上可以将部分路径定义为变量(至少在Python中是这样),而不是解析路径。
所以要处理'.../person/124/favorite':
class PersonHandler(webapp.RequestHandler):
def get(self, person_key, favorite):
person = Person.get(db.get(person_key))
person.Favorite = favorite
person.put()
application = webapp.WSGIApplication([('/person/([^/]+)/([^/]+)', PersonHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
https://stackoverflow.com/questions/7972715
复制