Flask路线

时间:2016-11-01 17:30:15

标签: python flask

以下面两条路线为例。

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/"

我希望看到的行为是案例二行为的&#39; <&#39; 。例如"/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我可以全局应用。也许是蓝图或网址规则?

3 个答案:

答案 0 :(得分:20)

使用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])

答案 1 :(得分:0)

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

app = Flask(__name__)

@app.route("/someplace/")
@app.route("/someplace")
def slash_agnostic():
    #code for both routes

答案 2 :(得分:0)

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

code {
  color: black;
  background-color: darken($background-color, 5%);
  border-radius: 4px;
  overflow: auto;
  padding-left: 5px;
}
相关问题