【问题标题】:Python Flask -- URL Encoded Leading Slashes causing 404 or 405Python Flask -- URL 编码的前导斜杠导致 404 或 405
【发布时间】:2014-07-01 20:51:36
【问题描述】:

我的应用程序经常将 URL 编码字符串作为 URL 参数。通常这些字符串看起来像带有前导斜杠的路径。即/file/foo。在烧瓶中,我有一个端点,它接受一个路径参数,我将 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)

如果我访问此 URL,这将非常有用:

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

returns:

GOT: cats/

但是带有 %2F 的前导斜杠在 GET 的情况下失败,404 和 405 在 POST 的情况下。换句话说,这个 404s:

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

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

【问题讨论】:

  • 恐怕我在使用 URL 编码的建议中是不正确的。过错。

标签: python flask


【解决方案1】:

在不定义自己的 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

【讨论】:

    【解决方案2】:

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

    第二个链接提供了一个patch在路由之后执行这个解码,但是没有合并。

    目前看来最好的解决方案是关注Martijn's answer here

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2016-11-28
      • 1970-01-01
      • 2010-10-10
      • 2011-11-12
      • 1970-01-01
      相关资源
      最近更新 更多