我正在尝试将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进行哪些更改?

最佳答案

这是我最终开始工作的代码。我需要做的改变对我来说并不明显:
我必须将配置从一个文件移到一个字典中,以便可以向其中添加分派器。
我必须在cherrypy.quickstart之前给cherrypy.mount打个电话。
我必须包括dispatcher.explicit = False
我希望其他处理这个问题的人都觉得这个答案有用。

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)

09-26 21:07
查看更多