URL路径末尾加斜杠和不加斜杠有明显区别吗?

3

我遇到的问题是当我运行一个类似于下面这样的 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/ 两个地址的访问问题。

同时,我也很想了解路径末尾是否加斜杆(/)的区别,比如上面的http://localhost:9999/hellohttp://localhost:9999/hello/,或者有时我们上传文件时会遇到这种情况。

1个回答

4
  • 路由路径是一个正则表达式,所以您可以将其设置为r'/hello/?',它将接受带斜杠和不带斜杠的URL。
  • 关于URL样式,我刚刚在SO上通过搜索找到了另一个问题,按投票排序:什么时候应该在我的URL中使用尾随斜杠?

1
请注意,虽然这是有效的正则表达式,并且在模式匹配方面会按照您的期望工作,但它会导致 URL 反向不正常(reverse_url() 输出将包括尾随的 ?)。我在谷歌搜索中找到了这个答案来解决这个反向 URL 问题。 :) - kitti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接