在我的第一个 Flask 应用程序中,我正在试验以斜杠结尾的 URL 与不以斜杠结尾的 URL,并且我看到了一些意外的浏览器行为。
我的 View 函数是这样的:
@app.route('/hello') def hello_world(): return 'Hello World!'
然后我可以转到
127.0.0.1:5000/hello
并查看“Hello World”。我将 URL 更改为:
@app.route('/hello/') def hello_world(): return 'Hello World!'
然后我可以转到
127.0.0.1:5000/hello
但浏览器重定向到127.0.0.1:5000/hello/
。我将 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/