Python Flask -- URL 编码的前导斜杠导致 404 或 405 [英] Python Flask -- URL Encoded Leading Slashes causing 404 or 405

查看:48
本文介绍了Python Flask -- URL 编码的前导斜杠导致 404 或 405的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My application frequently takes URL encoded strings as a URL parameter. Often these strings look like paths with a leading slash. IE /file/foo. In flask, I have an endpoint that takes a path parameter that I send a URL encoded path to. So I have something that looks like:

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,这很有效:

This works great if I visit this URL:

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

returns:

GOT: cats/

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

But a leading slash with %2F fails with 404 in the case of GET and 405 in the case of POST. In other words, this 404s:

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

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

In my research on this problem, I was lead to believe here that URL encoding was sufficient to sole the problem. However that doesn't appear to be the case.

推荐答案

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

This is because of how Werkzeug parses urls. It decodes the encoded slashes before parsing the route, so they still appear as leading slashes. There are bug reports about this:

第二个链接在路由后提供了一个补丁来执行这个解码,但它没有合并.

The second link provides a patch to perform this decoding after routing, but it is not merged.

目前看来最好的解决方案是遵循 Martijn 的在这里回答.

It looks like the best solution at this point is to follow Martijn's answer here.

这篇关于Python Flask -- URL 编码的前导斜杠导致 404 或 405的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆