在Flask路线的尾随斜线

syt*_*ech 16 python flask

以下面两条路线为例.

app = Flask(__name__)

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

@app.route("/someplace/")
def with_trailing_slash():
    #case two
Run Code Online (Sandbox Code Playgroud)

根据文档,以下内容被理解为:

  • 在第一种情况下,对路由的请求"/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
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更好的解决方案,比如某种类型的drop-in app配置,类似于strict_slashes=False我可以在全球范围内应用.也许是蓝图或网址规则?

Won*_*ket 33

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

app = Flask('my_app')
app.url_map.strict_slashes = False
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用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])
Run Code Online (Sandbox Code Playgroud)

  • 这看起来很有趣.这可能适用于解决方案.如果我采用这种方法,我可能首先检查斜线*less*路由是否存在重定向之前,以避免重定向到最终将成为404的URL.但是,是的,这看起来不错.我不确定每次为每条路线*注册一个函数来运行*的感觉.我正在权衡使用404错误处理程序,它将检查是否存在无条件路由,我认为只有在404发生时才会运行,并且与此相比可能会或可能不会产生性能影响. (2认同)

trp*_*pst 7

如果您希望以相同的方式处理两条路线,我会这样做:

app = Flask(__name__)

@app.route("/someplace/")
@app.route("/someplace")
def slash_agnostic():
    #code for both routes
Run Code Online (Sandbox Code Playgroud)

  • 如果“/someplace”是命名空间前缀怎么办? (2认同)

小智 7

您还可以在路由定义中使用选项 strict_slashes=False:

app.Flask(__name__)
@app.route("/someplace", strict_slashes=False)
# Your code goes here
Run Code Online (Sandbox Code Playgroud)