代码之家  ›  专栏  ›  技术社区  ›  hyperboreean

CherryPy和restfulwebapi

  •  12
  • hyperboreean  · 技术社区  · 15 年前

    稍后编辑:

    5 回复  |  直到 15 年前
        1
  •  11
  •   katericata    8 年前

    我不知道这是否是“最好”的方法,但我是这样做的:

    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())
    

    RESTResource 类并使用前缀为的同名方法处理所需的RESTful动词(GET、PUT、POST、DELETE) handle_ . 如果不处理特定的动词(如POST),基类将引发一个 405 Method Not Implemented

    vpaths 并传入任何查询字符串 params . 如果您需要 /foo/bar?woo=hoo , vpath[0] bar ,和 参数 {'woo': 'hoo'} .

        2
  •  7
  •   s4w3d0ff    8 年前

    更多信息可在CherryPy文档中找到: http://cherrypy.readthedocs.io/en/latest/tutorials.html#tutorial-7-give-us-a-rest

    下面还详细介绍了如何使用CherryPy工具发送和接收JSON: http://tools.cherrypy.org/wiki/JSON

        3
  •  2
  •   Ryne Everett CodedReality    11 年前

    所以你想转换/getOrders?使用Cherrypy将account=X&type=Y转换为/orders/account/type。

    我会尝试 http://cherrypy.readthedocs.org/en/latest/tutorial/REST.html 正如@Tomasz Blachowicz提到的,经过一些修改。

    请记住,您可以使用

    @cherrypy.expose
    def order(account=None, type=None):
        print account, type
    
    class Root(object):
        pass
    
    root = Root()
    root.orders = orders
    
    
    cherrypy.quickstart(root, '/')
    

    所以,如果你以中给出的例子为例 http://cherrypy.readthedocs.org/en/latest/tutorial/REST.html

    class Orders(object):
        exposed = True
        def __init__(self):
            pass
    
        def GET(self, account=None, type=None):
            #return the order list for this account type
            return getOrders(account, type)
    
        def PUT(self, account=None, type=None, orders=None):
            #Set the orders associated with account or something
            setOrders(account, type, orders)
    
    
    class Root(object):
        pass
    
    root = Root()
    root.orders = Orders()
    
    conf = {
        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': 8000,
        },
        '/': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
        },
    }
    
    cherrypy.quickstart(root, '/', conf)
    

    我喜欢这种方法,因为它很容易看到发生了什么,我相信,它回答了你的问题。

        4
  •  1
  •   dagw    15 年前

    我想你已经尝试过教程中提到的部分匹配。我发现,虽然不是很好,但大多数时候它确实能完成任务。

    除此之外,虽然我没试过,但Cherrypy显然支持 Routes (参见 http://www.cherrypy.org/wiki/PageHandlers ),这为您提供了各种RESTful选项。

        5
  •  1
  •   colinmarc    15 年前

    要回答第二个问题,您需要定义并公开一个默认方法:

    class getOrders(Object):
        def default(account, type):
            ...
    
        default.exposed = True
    

    使用此方法,getOrders/x/y将映射到 default(account='x', type='y')

    至于RESTful应用程序,我非常肯定默认页面处理程序将适用于此类应用程序。