python - 将 CherryPy 与路由调度一起使用

标签 python routes cherrypy

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

以下 python 代码使用标准 CherryPy 调度正确路由 /。我的目标是将相同的代码转换为使用 RoutesDispatcher 运行。我四处寻找我发现的片段,但未能找到使用路由的 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. 我必须将我的配置从一个文件移动到一个字典中,以便我可以将调度程序添加到其中。

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

  3. 我必须包含 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)

关于python - 将 CherryPy 与路由调度一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656286/

相关文章:

python - 日志记录和 CherryPy 可以共享相同的配置文件吗?

python - 有没有办法缩短这个 if 语句?

python - python 和 debian 9 的 Unicode 版本

ruby-on-rails - Rails 试图创建嵌套路由

javascript - module.exports 与对象

python - Apache 套接字没有关闭?

python - 集成 CSS 和 CherryPy : How to fix the 404 "/" Not Found Error?

python - Django 中 QuerySet 中特定列的平均重复项

python - 如何在python中的sql查询中使用MySQL模式匹配和绑定(bind)参数?

javascript - 如何在 HERE Map API 上获取方向多段线而不是实线