Python Flask - URL编码的前导斜杠导致404或405

时间:2014-07-01 20:51:36

标签: python flask

我的应用程序经常将URL编码的字符串作为URL参数。通常这些字符串看起来像带有前导斜杠的路径。 IE /file/foo。在flask中,我有一个端点,它采用我发送URL编码路径的路径参数。所以我有一些看起来像:

import flask
app = flask.Flask("Hello World")

@app.route("/blah/<path:argument>", methods=["GET"])
def foo(argument):
    return "GOT: %s" % argument

if __name__ == "__main__":
    app.run(debug=True)

如果我访问此网址,则效果很好:

http://localhost:5000/blah/cats%2F

returns:

GOT: cats/

但是%2F的前导斜线在GET的情况下失败,404在POST的情况下失败。换句话说,这是404s:

http://localhost:5000/blah/%2Fcats

在我对此问题的研究中,我始终相信here URL编码足以解决问题。然而,情况似乎并非如此。

2 个答案:

答案 0 :(得分:1)

这是因为Werkzeug如何解析网址。它在解析路由之前解码编码的斜杠,因此它们仍然显示为前导斜杠。有关于此的错误报告:

第二个链接提供了一个补丁,用于在路由后执行此解码,但它没有合并。

此时看来最好的解决方案是遵循Martijn's answer here

答案 1 :(得分:0)

在没有定义自己的PathConverter的情况下解决这个问题的一种方法是使用两个路由过滤器:

import flask
app = flask.Flask("Hello World")

@app.route("/blah/<path:argument>", methods=["GET"])
@app.route("/blah//<path:argument>", methods=["GET"])
def foo(argument):
    return "GOT: %s" % argument

if __name__ == "__main__":
    app.run(debug=True)

点击:

http://localhost:5000/blah/%2Fcats

给我:

GOT: cats

并且:

http://localhost:5000/blah//cats

给我:

GOT: cats

但是更好(更干净)的解决方案可能是本SO答案中描述的解决方案:Flask route using path with leading slash

相关问题