Cherrypy 对未安装或不正确的响应 url

Cherrypy respond to unmounted or incorrect url

我被以下问题搞糊涂了:

我有一个 class TestLink 安装到 url /testlink

class TestLink(object):
    exposed = True
    @cherrypy.expose
    @cherrypy.tools.accept(media='text/plain')
    def GET(self, var=None, **params):
        return "data:1,2\nzelta:3,4"

if __name__ == '__main__':
    app = cherrypy.tree.mount(
        TestLink(), '/testlink',
        "test.config"
    )

我在 "test.config" 文件中使用了 Cherrypy rest 调度程序:

request.dispatch = cherrypy.dispatch.MethodDispatcher()

当我点击启动服务器并点击 url“http://127.0.0.1:8080/testlink", I get the result. However, I also get result if I hit the url http://127.0.0.1:8080/testlink/x or "http://127.0.0.1:8080/testlink/anything_string". Why does this happen, shouldn't only the url "http://127.0.0.1:8080/testlink”return 数据时?

鉴于您的代码示例,如果您尝试访问 http://127.0.0.1:8080/testlink/foo/bar cherrypy 将响应 404 Not Found。这是因为 MethodDispatcher 将 'foo' 解释为参数 'var' 的值,正如您在 GET() 的签名中指定的那样。

这是您的示例的修改后的工作版本:

import cherrypy

config = {
    '/': {
        'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
        'tools.trailing_slash.on': False,
    }
}

class TestLink(object):
    exposed = True

    ## not necessary, you want to use MethodDispatcher. See docs.
    #@cherrypy.expose
    @cherrypy.tools.accept(media='text/plain')
    def GET(self, var=None, **params):
        print var, params
        return "data:1,2\nzelta:3,4"

if __name__ == '__main__':
    app = cherrypy.tree.mount(TestLink(), '/testlink', config)
    cherrypy.engine.start()
    cherrypy.engine.block()

现在尝试http://127.0.0.1:8080/testlink/foo,它会打印

foo {}

而点击 http://127.0.0.1:8080/testlink/foo/bar 将导致 404。

请参阅文档 https://cherrypy.readthedocs.org/en/3.3.0/refman/_cpdispatch.html,或者您当然可以自己研究模块 cherrypy/_cpdispatch.py 中的代码。