Recently started using CherryPy and I'm having a difficult creating subpages.
The structure I'd like is a root page /
, an overview page /resources
, and then individual resource pages /resources/my_resource
. I likely will have other pages /my_page
and maybe/my_page/my_page2
.
I first tried using a 'Home' page class to handle the top level pages with a 'Resource' class decorated with cherrypy.popargs
to handle the resource pages.
I started CherryPy as follows:
cherrypy.tree.mount(Home(), '/', home_conf)
cherrypy.tree.mount(Resource(), '/resource/', resource_conf)
cherrypy.engine.start()
cherrypy.engine.block()
This replaced the /resource/
page with the individual resource pages. i.e. they were served at /my_resource/
instead of /resource/my_resource
I believe I can workaround this using the cp_dispatch
method, but it seems clunky handling different urls in different ways. Is there a better way to handle subpages with either variable or static structure?
Came across an answer. cp_dispatch
can work, but there's a construct in CherryPy that does precisely what we want.
ROUTES = cherrypy.dispatch.RoutesDispatcher()
ROUTES.connect(name='home', route="/my_route",
controller=MyController(), action='index',
conditions=dict(method=["GET"]))
Then we just need to add the key pair '/': {'request.dispatch': ROUTES}
to the config we send CherryPy.
The controller argument should point to any container class owning the function that returns the desired content. The action argument is that function, which should have the regular CherryPy decorator.
EDIT
Also worth noting I think this requires the routes
package, not included or dependent on CherryPy.