尾随斜杠在 Flask 路径规则中触发 404 [英] Trailing slash triggers 404 in Flask path rule

查看:20
本文介绍了尾随斜杠在 Flask 路径规则中触发 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 /users 下的任何路径重定向到静态应用程序.下面的视图应该捕获这些路径并提供适当的文件(它只是打印此示例的路径).这适用于 /users/users/604511/users/604511/action.为什么路径 /users/ 会导致 404 错误?

I want to redirect any path under /users to a static app. The following view should capture these paths and serve the appropriate file (it just prints the path for this example). This works for /users, /users/604511, and /users/604511/action. Why does the path /users/ cause a 404 error?

@bp.route('/users')
@bp.route('/users/<path:path>')
def serve_client_app(path=None):
    return path

推荐答案

您的 /users 路由缺少尾部斜杠,Werkzeug 将其解释为不匹配尾部斜杠的显式规则.添加尾部斜杠,如果 url 没有,Werkzeug 将重定向,或者设置 strict_slashes=False 和 Werkzeug 将匹配带有或不带有斜杠的规则.

Your /users route is missing a trailing slash, which Werkzeug interprets as an explicit rule to not match a trailing slash. Either add the trailing slash, and Werkzeug will redirect if the url doesn't have it, or set strict_slashes=False on the route and Werkzeug will match the rule with or without the slash.

@app.route('/users/')
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get('/users'))  # 302 MOVED PERMANENTLY (to /users/)
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK

@app.route('/users', strict_slashes=False)
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get('/users'))  # 200 OK
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK

<小时>

您还可以为所有 URL 设置 strict_slashes.

app.url_map.strict_slashes = False

但是,在大多数情况下,您应该避免禁用严格的斜线.文档解释了原因:

However, you should avoid disabling strict slashes in most cases. The docs explain why:

即使省略了尾部斜杠,这种行为也允许相对 URL 继续工作,这与 Apache 和其他服务器的工作方式一致.此外,网址将保持唯一,这有助于搜索引擎避免将同一页面编入两次索引.

This behavior allows relative URLs to continue working even if the trailing slash is omitted, consistent with how Apache and other servers work. Also, the URLs will stay unique, which helps search engines avoid indexing the same page twice.

这篇关于尾随斜杠在 Flask 路径规则中触发 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆