Skip to main content
 首页 » 编程设计

python之使用带有路径前缀的 cherrypy 公开函数

2024年10月24日11Renyi-Fan

在 cherrypy 中有没有办法将函数 foo_test() 公开为服务器上的 /foo/test 端点?

下面的示例公开了两个端点 /index 和 /foo_test:

class Test(object): 
 
  @cherrypy.expose 
  def index(self): 
 
  @cherrypy.expose 
  def foo_test(self): 

注意:

  • 我已经在 @cherrypy.expose(['foo/test']) 中使用别名进行了测试,但别名只允许字符串和字符串列表。

请您参考如下方法:

最后,我不得不重写 _cp_dispatch,如 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):