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

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

问题描述

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

  import flask 
app = flask.Flask(Hello World)
$ b $ app_route(/ blah /< path:argument>,methods = [GET])
def foo(argument):
returnGOT: %s%参数

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

如果我访问这个URL,这个效果很好:

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

回报:

GOT:猫/

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

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

在我对这个问题的研究中,我导致相信这里,URL编码足以解决这个问题。然而,这似乎并不是这样。

解决方案

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


  • https://github.com/mitsuhiko/flask/issues/900

  • $ / $>
    / $

    第二个链接提供了一个在路由后执行这个解码的补丁,但是它不会被合并。



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


    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)
    

    This works great if I visit this URL:

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

    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
    

    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.

    解决方案

    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.

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

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

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