gpt4 book ai didi

python - Flask 路由中的尾部斜杠

转载 作者:太空狗 更新时间:2023-10-29 17:25:02 25 4
gpt4 key购买 nike

以下面两条路线为例

app = Flask(__name__)

@app.route("/somewhere")
def no_trailing_slash():
#case one

@app.route("/someplace/")
def with_trailing_slash():
#case two

根据 the docs理解如下:

  • 在第一种情况下,对路由 "/somewhere/" 的请求将返回 404 响应。 "/somewhere" 有效。

  • 在第二种情况下,"/someplace/" 是有效的,"/someplace" 将重定向到 "/someplace/"

我希望看到的行为是案例二 行为的“相反”。例如"/someplace/" 将重定向到 "/someplace" 而不是相反。有没有办法定义采取这种行为的路线?

根据我的理解,可以在路由上设置 strict_slashes=False 以有效地获得与案例一相同的案例二的相同行为,但我想做的是将重定向行为设置为总是重定向到没有尾部斜线的 URL。

我想过使用的一种解决方案是对 404 使用错误处理程序,类似这样。 (不确定这是否有效)

@app.errorhandler(404)
def not_found(e):
if request.path.endswith("/") and request.path[:-1] in all_endpoints:
return redirect(request.path[:-1]), 302
return render_template("404.html"), 404

但我想知道是否有更好的解决方案,例如某种类似于 strict_slashes=False 的嵌入式应用程序配置,我可以在全局范围内应用。也许是蓝图或 URL 规则?

最佳答案

您使用 strict_slashes 进行了正确的跟踪,您可以在 Flask 应用程序本身上对其进行配置。这将为创建的每个路由将 strict_slashes 标志设置为 False

app = Flask('my_app')
app.url_map.strict_slashes = False

然后您可以使用 before_request 来检测重定向的尾随 /。使用 before_request 将允许您不需要将特殊逻辑分别应用于每个路由

@app.before_request
def clear_trailing():
from flask import redirect, request

rp = request.path
if rp != '/' and rp.endswith('/'):
return redirect(rp[:-1])

关于python - Flask 路由中的尾部斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40365390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com