【问题标题】:Is there any clear difference in url path with the path closed with slash or not?url路径与用斜杠关闭的路径是否有明显区别?
【发布时间】:2013-12-22 09:05:38
【问题描述】:

我遇到的标题问题是当我使用 tornado 运行一个 hello-world 示例时 像这样:

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=9999, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!')

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/hello", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

我运行了这段代码并运行了如下命令: curl http://localhost:9999/hello,获得了 200 HTTP 状态。

但是当我运行用斜杠关闭路径的命令时: curl http://localhost:9999/hello/,它得到了 404 HTTP 状态。

我知道代码中的问题可能是这一行:

app =  tornado.web.Application(handlers=[(r"/hello", IndexHandler)])

所以我想知道是否有一种简单的方法可以通过同时访问 http://localhost:9999/hellohttp://localhost:9999/hello/ 来修复它。

我也很想了解 url 路径与是否用斜杠(/)关闭的路径的区别,比如上面的 http://localhost:9999/hellohttp://localhost:9999/hello/ 或者有时当我们 put 文件时。

【问题讨论】:

    标签: url web path tornado


    【解决方案1】:
    • 路由路径是一个正则表达式,因此您可以将其设置为r'/hello/?',它既可以接受斜线,也可以不接受斜线。
    • 关于 URL 样式,还有一个关于 SO 的问题,我刚刚通过搜索发现,按投票排序:When should I use a trailing slash in my URL?

    【讨论】:

    • 请注意,虽然这是有效的正则表达式,并且在模式匹配方面会达到您的预期,但它会弄乱 URL 反转(reverse_url() 的输出将包括尾随 ?)。我在谷歌搜索解决这个反向 URL 问题时找到了这个答案。 :)
    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 2014-08-27
    • 2016-11-20
    • 2010-12-29
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多