hyp*_*ean 13 python rest cherrypy
在CherryPy中创建RESTful Web API的最佳方法是什么?我一直在寻找几天,似乎没什么好看的.对于Django来说,似乎有很多工具可以做到这一点,但不是CherryPy或我不知道它们.
稍后编辑:我应该如何使用Cherrypy将/ getOrders?account = X&type = Y等请求转换为/ orders/account/type之类的内容?
car*_*pie 11
我不知道这是否是"最好的"方式,但这是我的方式:
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:<br/>" + '<br/>'.join(vpath)
query = ['%s=>%s' % (k,v) for k,v in params.items()]
retval += "<br/>Query String Elements:<br/>" + \
'<br/>'.join(query)
return retval
class Root(object):
foo = FooResource()
@cherrypy.expose
def index(self):
return "REST example."
cherrypy.quickstart(Root())
Run Code Online (Sandbox Code Playgroud)
您只需从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
我假设您已经尝试过教程中讨论的部分匹配。我发现虽然不是很好,但大多数时候它确实可以完成工作。
除此之外,虽然我还没有尝试过,但 Cherrypy 显然支持 路由(请参阅http://www.cherrypy.org/wiki/PageHandlers),它为您提供了各种 RESTful 选项。
| 归档时间: |
|
| 查看次数: |
16275 次 |
| 最近记录: |