Skip to content Skip to sidebar Skip to footer

Friendly Url For A Rest Webservice With Cherrypy

I'm making a RESTful WebService using CherryPy 3 but I encounter a problem : I want to be able to answer requests like : /customers/1/products/386 meaning I want all the product wi

Solution 1:

CherryPy uses a tree-based mapper which does not accommodate well with segments that have no physical reality as a Python object, here your /1/ segment.

With that said, CherryPy does provide functionalities to reach your goal.

  • Swap to a more explicit mapper such as selector or routes.
  • Use _cp_dispatch
  • Use cherrypy.popargs

Let's focus on the last two.

_cp_dispatch is a special method you declare in any of your controller to massage the remaining segments before CherryPy gets to process them. This offers you the capacity to remove, add or otherwise handle any segment you wish and, even, entirely change the remaining parts.

import cherrypy

classBand(object):def__init__(self):
        self.albums = Album()

    def_cp_dispatch(self, vpath):
        if len(vpath) == 1:
            cherrypy.request.params['name'] = vpath.pop()
            returnselfif len(vpath) == 3:
            cherrypy.request.params['artist'] = vpath.pop(0)  # /band name/
            vpath.pop(0) # /albums/
            cherrypy.request.params['title'] = vpath.pop(0) # /album title/returnself.albums

        return vpath

    @cherrypy.expose
    defindex(self, name):
        return'About %s...' % name

classAlbum(object):@cherrypy.expose
    defindex(self, artist, title):
        return'About %s by %s...' % (title, artist)

if __name__ == '__main__':
    cherrypy.quickstart(Band())

cherrypy.popargs is more straightforward as it gives a name to any segment that CherryPy wouldn't be able to interpret otherwise. This makes the matching of segments with page handler signatures easier and help CherryPy understand the structure of your URL.

import cherrypy

@cherrypy.popargs('name')classBand(object):
    def__init__(self):
        self.albums = Album()

    @cherrypy.exposedefindex(self, name):
        return'About %s...' % name

@cherrypy.popargs('title')classAlbum(object):
    @cherrypy.exposedefindex(self, name, title):
        return'About %s by %s...' % (title, name)

if __name__ == '__main__':
    cherrypy.quickstart(Band())

In both cases go to http://whatevertomakesohappy.com:8080/nirvana/ and then http://whatevertomakesohappy.com:8080/nirvana/albums/nevermind/

Both are powerful but which one you want to use is up to you. For simple URLs, popargs is likely to be much easier in my book. Obviously both can be used concurrently.

Solution 2:

Thanks for your answer Sylvain. You've led me to the answer I was looking for. I used the RouteDispatcher like this :

    self.connect("cust_products", "/customers/{cust_id}/products/",
                 controller=CustomerController(),
                 action='index',
                 conditions=dict(method=['GET']))

    self.connect("cust_products", "/customers/{cust_id}/products/{id}",
                 controller=CustomerController(),
                 action='show',
                 conditions=dict(method=['GET']))

    self.connect("cust_products", "/customers/{cust_id}/products/",
                 controller=CustomerController(),
                 action='create',
                 conditions=dict(method=['POST']))

    self.connect("cust_products", "/customers/{cust_id}/products/{id}",
                 controller=CustomerController(),
                 action='update',
                 conditions=dict(method=['PUT']))


    self.connect("cust_products", "/customers/{cust_id}/products/{id}",
                 controller=CustomerController(),
                 action='delete',
                 conditions=dict(method=['DELETE']))

Post a Comment for "Friendly Url For A Rest Webservice With Cherrypy"