使用CherryPy和路由调度

时间:2011-10-05 03:02:51

标签: python routes cherrypy

我正在尝试将CherryPy应用程序从标准的CherryPy调度切换到RoutesDispatcher。

以下python代码使用标准的CherryPy调度正确路由/。我的目标是将相同的代码转换为使用RoutesDispatcher运行。我已经找到了我发现的片段,但是还没能找到使用Routes的CherryPy应用程序的完整示例。

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')

我试图结合我发现的各种部分教程中的代码而没有任何运气。

我必须对__main__进行哪些更改才能通过RoutesDispatcher加载和路由?

1 个答案:

答案 0 :(得分:4)

这是我最终开始工作的代码。我需要做出的改变对我来说并不是很明显:

  1. 我不得不将配置从文件移到字典中,以便我可以将调度程序添加到字典中。

  2. 我必须在cherrypy.quickstart之前调用cherrypy.mount。

  3. 我必须加入dispatcher.explicit = False

  4. 我希望处理此问题的其他任何人都认为这个答案很有帮助。

    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)