帮助我更好地理解CherryPy PageHandlers

时间:2021-09-08 03:10:16

Let's say I have some code (using CherryPy) that looks like this:

假设我有一些代码(使用CherryPy),如下所示:

import cherrypy

class Names:
    def index(self, name=None):
        return "Names.index:  " + str(name)
    index.exposed = True

class Root:
    def index(self):
        return "This is the root"
    index.exposed = True

if __name__ == "__main__":
    root = Root()

    root.names = Names()

    cherrypy.tree.mount(root, '/')
    cherrypy.engine.start()
    cherrypy.engine.block()

If I hit the url http://localhost:8080/names/, I see Names.index: None, which is fine. That means the Names() class is being called.

如果我点击网址http:// localhost:8080 / names /,我看到Names.index:None,这很好。这意味着正在调用Names()类。

But, if I go to http://localhost:8080/names/mark, I get a 404 Error instead of the Names.index: mark I was expecting.

但是,如果我转到http:// localhost:8080 / names / mark,我得到404错误而不是Names.index:我期待的标记。

This confuses me because, according to the PageHandler documentation:

这让我感到困惑,因为根据PageHandler文档:

When a request is processed, the URI is split into its components, and each one is matched in order against the nodes in the tree. Any trailing components are "virtual path" components and are passed as positional arguments.

处理请求时,URI将拆分为其组件,并且每个组件将按顺序与树中的节点进行匹配。任何尾随组件都是“虚拟路径”组件,并作为位置参数传递。

Now let's say I change the Names() class to look like this:

现在让我们说我将Names()类更改为如下所示:

class Names:
    def index(self, name=None):
        return "Names.index:  " + str(name)
    index.exposed = True

    def name(self, name=None):
        return "Names.name:  " + str(name)
    name.exposed = True

Now I can go to http://localhost:8080/names/name/mark and I see Names.name: mark.

现在我可以转到http:// localhost:8080 / names / name / mark,我看到Names.name:mark。

Can someone explain what's happening here?

有人能解释一下这里发生了什么吗?

1 个解决方案

#1


The index method is an exception to the partial matching rules. You can use the default method instead, or in this particular example make names a method itself.

索引方法是部分匹配规则的例外。您可以使用默认方法,或者在此特定示例中,将名称设置为方法本身。

#1


The index method is an exception to the partial matching rules. You can use the default method instead, or in this particular example make names a method itself.

索引方法是部分匹配规则的例外。您可以使用默认方法,或者在此特定示例中,将名称设置为方法本身。