在CherryPy中创建RESTful Web API的最佳方法是什么?我一直在寻找几天,似乎没什么好看的.对于Django来说,似乎有很多工具可以做到这一点,但不是CherryPy或我不知道它们.
稍后编辑:我应该如何使用Cherrypy将/ getOrders?account = X&type = Y等请求转换为/ orders/account/type之类的内容?
我不知道这是否是"最好的"方式,但这是我的方式:
import cherrypy class RESTResource(object): """ Base class for providing a RESTful interface to a resource. To use this class, simply derive a class from it and implement the methods you want to support. The list of possible methods are: handle_GET handle_PUT handle_POST handle_DELETE """ @cherrypy.expose def default(self, *vpath, **params): method = getattr(self, "handle_" + cherrypy.request.method, None) if not method: methods = [x.replace("handle_", "") for x in dir(self) if x.startswith("handle_")] cherrypy.response.headers["Allow"] = ",".join(methods) raise cherrypy.HTTPError(405, "Method not implemented.") return method(*vpath, **params); class FooResource(RESTResource): def handle_GET(self, *vpath, **params): retval = "Path Elements:
" + '
'.join(vpath) query = ['%s=>%s' % (k,v) for k,v in params.items()] retval += "
Query String Elements:
" + \ '
'.join(query) return retval class Root(object): foo = FooResource() @cherrypy.expose def index(self): return "REST example." cherrypy.quickstart(Root())
您只需从RESTResource
类派生并使用前缀相同名称的方法处理您想要的任何RESTful动词(GET,PUT,POST,DELETE)handle_
.如果您不处理特定动词(例如POST),则基类将为您引发405 Method Not Implemented
错误.
传入路径项并传入vpaths
任何查询字符串params
.使用上面的示例代码,如果您要求/foo/bar?woo=hoo
,vpath[0]
将会是bar
,并且params
将会{'woo': 'hoo'}
.
因为HTTP定义了这些调用方法,所以使用CherryPy实现REST的最直接方法是使用MethodDispatcher而不是默认调度程序.
更多内容可以在CherryPy文档中找到:http: //cherrypy.readthedocs.io/en/latest/tutorials.html#tutorial-7-give-us-a-rest
以下是有关如何使用CherryPy Tools发送和接收JSON的详细说明:http: //tools.cherrypy.org/wiki/JSON