【问题标题】:Trailing Slash tool in CherryPy 3.2 not adding a trailing slashCherryPy 3.2 中的斜杠工具未添加斜杠
【发布时间】:2012-04-23 06:56:15
【问题描述】:

我无法让 trailing_slash 工具工作。我玩过 trailing_slash 工具的选项似乎没有任何效果。 我正在使用 CherryPy 3.2.2 和 Routes 1.13。我想拥有一个 添加了斜杠。调试输出中没有错误。

如果我去 127.0.0.1:8080/blog/ 它可以工作,但是如果我去 到 127.0.0.1:8080/blog 它没有。

我的配置是:

conf = {
'/': {
    'request.dispatch': setup_routes(),
    # This trailing slash stuff has no effect :(
    'tools.trailing_slash.on': True,
    'tools.trailing_slash.missing': True,
    'tools.trailing_slash.status': 301,
},
'/static': {
       'tools.staticdir.on': True,
       'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),
       'tools.staticdir.dir': 'static'
   }
}

示例路线是:

routes = [["blog_index", "/blog/", {'controller': BlogController(), 'action': 'index','entry_id': 'index'}],]

谁能看到我做错了什么?是否有错误或缺乏 必要的文件? trailing_slash 工具是否可以与 Routes Dispatcher 一起使用?

完整的源代码:https://bitbucket.org/ddevine/icdy/src

【问题讨论】:

    标签: python routing cherrypy trailing-slash


    【解决方案1】:

    尾部斜杠工具不适用于 Routes Dispatcher。尾部斜杠工具期望无论选择什么调度程序,都会将 cherrypy.request.is_index 设置为 True 或 False,看起来 RoutesDispatcher 类根本不这样做。因此,is_index 保留为 None,而尾部斜杠 Tool 什么也不做。对 Routes 有很好了解的人可能会在 CherryPy 代码库中修复它,或者编写自己的调度程序来设置 is_index,或者尝试编写另一个工具来修复 is_index。

    【讨论】:

    • 这很不幸。看起来我将编写一个自定义调度程序。希望我在尝试这样做时不会发现更多无证好东西。
    • 我查看了代码。在 RoutesDispatcher find_handler 中的result = self.mapper.match(path_info) 之后,我输入: if result == None: result = self.mapper.match(path_info+"/")` 这似乎可行,尽管出于我的原因,这可能是一件非常愚蠢的事情还不知道。
    • @DanielDevine 您可能不想这样做,因为带有斜杠的路径和没有斜杠的路径可以在 Routes 中做非常不同的事情。如果要确保正确性,这不是一个好主意。最好配置你的反向代理网络服务器,在你想要的任何路径上添加一个斜杠。
    【解决方案2】:

    问了很久,但这里有一种方法可以让它工作:

    def index(index=True):
        cherrypy.request.is_index = index
    cherrypy.tools.index = cherrypy.Tool('on_start_resource', index)
    
    config = {
        ...
            'tools.trailing_slash.status': 307,
            'tools.index.on': True,
        ...
    }
    

    【讨论】:

      【解决方案3】:

      Routes 中没有“索引”的概念,因为您可以定义同一路径的 2 个连接,一个带有斜杠,一个没有,并将它们连接到 2 个完全不同的控制器和/或操作。在现实生活中你不会这样做,但在 Routes 中是可能的,所以真的没有一个好方法可以改变 trailing_slash 工具来处理这个问题。

      恕我直言,trailing_slash 工具有点欠缺,它可能应该提升到位于默认 WSGI 中间管道前面的 WSGI 中间件的级别,就像现在 CherryPy 中的 InternalRedirect 中间件一样。例如,如果您在 script_name 下安装了 RouteDispatcher,则不能将 trailing_slash 工具放在任何地方让 CP 在 script_name 后放置一个斜杠,因为 Routes 中的所有路由都必须以斜杠开头,它会抛出一个如果您尝试匹配时 path_info 为空字符串,则发生 RoutesException。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 2012-01-12
        • 2015-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多