python - 如何使用 '/' 设计 Flask URL 路径

标签 python url flask

在我的第一个 Flask 应用程序中,我正在试验以斜杠结尾的 URL 与不以斜杠结尾的 URL,并且我看到了一些意外的浏览器行为。

  1. 我的 View 函数是这样的:

    @app.route('/hello')
    def hello_world():
        return 'Hello World!'
    

    然后我可以转到 127.0.0.1:5000/hello 并查看“Hello World”。

  2. 我将 URL 更改为:

    @app.route('/hello/')
    def hello_world():
        return 'Hello World!'
    

    然后我可以转到 127.0.0.1:5000/hello 但浏览器重定向到 127.0.0.1:5000/hello/

  3. 我将 URL 改回/hello:

    @app.route('/hello')
    def hello_world():
        return 'Hello World!'
    

然后我无法访问 /hello /hello/。当我访问 127.0.0.1:5000/hello 时,浏览器仍然重定向127.0.0.1:5000/hello/ 并且响应是404. 除非回滚到第 2 步,否则我什么都看不到。

这是怎么回事?

最佳答案

引自(稍作修改)section of the docs :

Unique URLs / Redirection Behavior

Though [your rules] look rather similar, they differ in their use of the trailing slash in the URL definition. In [your step #2], the canonical URL for the [hello_world] endpoint has a trailing slash. In that sense, it is similar to a folder on a file system. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.

这意味着第 2 步中的 Flask 将使用 301 Moved redirect 重定向 /hello URL .这是一个永久重定向,大多数浏览器都会缓存它。这就是为什么即使您更改了代码(在第 3 步中),浏览器仍会请求 /hello/,即使您请求的是 /hello(因为当它在第 2 步这样做时,Flask 告诉它 /hello 已经移动/hello/。)

在这种情况下,最简单的解决方案是清除浏览器的缓存 - 这会删除重定向的“内存”,一切都会重新开始。

就我个人而言,我使用 /directory/ 样式的 URL 来表示应该包含其他资源的资源,并使用 /leaf 来表示没有更多子资源的资源。

关于python - 如何使用 '/' 设计 Flask URL 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37017218/

相关文章:

python - 在 Flask 中创建 webhook

javascript - 如何使用递归遍历嵌套数组?

python - future 警告 : The default value of regex will change from True to False in a future version

python - 理解 Tensorflow 中的 while 循环

python - 在 tensorflow 中,有没有一种方法可以在构建图形时找出元素输出的形状(排名)?

javascript - 将 URL 分解为其组成部分

python - 如何将变量传递到 FLASK 中的另一条路线

php - %22(双引号)突然添加到 url

基于 URL 路径的 Javascript/jQuery 导航

python - 处理表单之间的数据