我是CherryPy的新手。我使用默认调度程序,其URL结构类似于:
root = Root()
root.page1 = Page1()
root.page1.apple = Apple()
root.page2 = Page2()
root.page2.orange = Orange()
Orange
呈现模板,其中我需要指向Apple
的链接。我可以硬编码/page1/apple/
。但是,如何以干燥的方式获取Apple
的网址?
可以使用CherryPy中的默认调度程序完成,还是只能使用Routes调度程序?
(我来自Django世界,人们会为此目的使用reverse()
。)
答案 0 :(得分: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()