Search code examples
pythonroutescherrypy

Using CherryPy with Routes dispatching


I'm trying to switch a CherryPy application from standard CherryPy dispatching to RoutesDispatcher.

The following python code routes /correctly using standard CherryPy dispatching. My goal is to convert this same code to run using RoutesDispatcher. I've flailed around with snippets I've found but have not been able to find a complete example of a CherryPy application using Routes.

class ABRoot:  

    def index(self):
        funds = database.FundList()
        template = lookup.get_template("index.html")
        return template.render(fund_list=funds)

index.exposed = True 

if __name__ == '__main__':
    cherrypy.quickstart(ABRoot(), '/', 'ab.config')

I have flailed around trying to combine code from various partial tutorials that I've found without any luck.

What changes do I have to make to __main__ to load and route via RoutesDispatcher?


Solution

  • Here is the code that I eventually got working. Changes I needed to make that were not immediately obvious to me:

    1. I had to move my configuration from a file to a dictionary so that I could add the dispatcher to it.

    2. I had to include a call to cherrypy.mount before cherrypy.quickstart.

    3. I had to include dispatcher.explicit = False

    I hope anyone else dealing with this issue finds this answer helpful.

    class ABRoot:  
    
         def index(self):
             funds = database.FundList()
             template = lookup.get_template("index.html")
             return template.render(fund_list=funds)
    
    if __name__ == '__main__':
    
    
         dispatcher = cherrypy.dispatch.RoutesDispatcher()
         dispatcher.explicit = False
         dispatcher.connect('test', '/', ABRoot().index)
    
         conf = {
        '/' : {
            'request.dispatch' : dispatcher,
            'tools.staticdir.root' : "C:/Path/To/Application",
            'log.screen' : True
        },
        '/css' : {
            'tools.staticdir.debug' : True,
            'tools.staticdir.on' : True,
            'tools.staticdir.dir' : "css"
        },
        '/js' : {
            'tools.staticdir.debug' : True,
            'tools.staticdir.on' : True,
            'tools.staticdir.dir' : "js"
        }
         }
    
         #conf = {'/' : {'request.dispatch' : dispatcher}}
    
         cherrypy.tree.mount(None, "/", config=conf) 
         cherrypy.quickstart(None, config=conf)