Search code examples
pythoncherrypy

Expose a function using cherrypy with a path prefix


Is there a way in cherrypy to expose the function foo_test() as a /foo/test endpoint on the server?

The example below exposes two endpoints /index and /foo_test:

class Test(object):

  @cherrypy.expose
  def index(self):

  @cherrypy.expose
  def foo_test(self):

Note:

  • I have tested using alias in @cherrypy.expose(['foo/test']) but only strings and list of strings are allowed for an alias.

Solution

  • In the end I had to override the _cp_dispatch as explained in http://docs.cherrypy.org/en/latest/advanced.html#the-special-cp-dispatch-method

    class Test(object):
    
      def __init__(self):
           self.foo = Foo()
    
      def _cp_dispatch(self, vpath):
           if len(vpath) == 1:
                return self
           if len(vpath) == 2:
                return self.foo
           return self
    
      @cherrypy.expose
      def index(self):
    
    class Foo(object):
    
      @cherrypy.expose
      def test(self):