2

我是 CherryPy 的新手。我正在使用默认调度程序,其 URL 结构类似于:

root = Root()
root.page1 = Page1()
root.page1.apple = Apple()
root.page2 = Page2()
root.page2.orange = Orange()

Orange呈现一个模板,我需要在其中链接到Apple. 我可以硬编码/page1/apple/。但是我怎样才能Apple以 DRY 的方式获取 URL?

这可以使用 CherryPy 中的默认调度程序完成,还是只能使用 Routes 调度程序?

(我来自 Django 世界,人们会使用reverse()它。)

4

1 回答 1

2

您可以通过以下方式访问已安装的应用程序

cherrypy.tree.apps[mount_point].root

root始终是挂载点的挂载实例。所以反向函数看起来像:

def reverse(cls):
    # get link to a class type
    for app_url in cherrypy.tree.apps.keys():
        if isinstance(cherrypy.tree.apps[app_url].root, cls):
            # NOTE: it will return with the first mount point of this class
            return app_url

请在下面找到使用您的类的示例代码。http://localhost:8080/page4/orange/打印出来{ Orange and the link to apple: : "/page3/apple" }

import cherrypy

link_to_apple_global = ''

class Orange(object):
    def __init__(self):
        pass
    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self):
        return {"Orange and the link to apple: ": link_to_apple_global}
class Page2(object):

    def __init__(self):
        pass
    @cherrypy.expose
    def index(self):
        return "Page2"
class Apple(object):

    def __init__(self):
        pass
    @cherrypy.expose
    def index(self):
        return "Apple"

class Page1(object):

    def __init__(self):
        pass
    @cherrypy.expose
    def index(self):
        return "Page1"

class Root(object):

    def __init__(self):
        pass
    @cherrypy.expose
    def index(self):
        return "Root"            

def reverse(cls):
    #return cherrypy.tree.apps.keys()
    #return dir(cherrypy.tree.apps[''].root)
    #return dir(cherrypy.tree.apps['/page3/apple'].root)
    # get link to apple
    for app_url in cherrypy.tree.apps.keys():
        if isinstance(cherrypy.tree.apps[app_url].root, cls):
            # NOTE: it will return with the first instance
            return app_url

root = Root()
root.page1 = Page1()
root.page1.apple = Apple()
root.page2 = Page2()
root.page2.orange = Orange()

cherrypy.tree.mount(root, '/')
# if you do not specify the mount points you can find the objects
# in cherrypy.tree.apps[''].root...
cherrypy.tree.mount(root.page1, '/page4')
cherrypy.tree.mount(root.page2, '/page3')
cherrypy.tree.mount(root.page2.orange, '/page4/orange')
cherrypy.tree.mount(root.page1.apple, '/page3/apple')

link_to_apple_global = reverse(Apple)

cherrypy.engine.start()
cherrypy.engine.block()
于 2013-01-16T07:35:53.387 回答