Python Flask -- URL Encoded Leading Slashes causing 404 or 405

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.


ANSWERS:


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.


One way to get around this without defining your own PathConverter is having two route filters:

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)

Hitting this with:

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

Gives me:

GOT: cats

And with:

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

Gives me:

GOT: cats

But a better (cleaner) solution is probably the one described in this SO answer: Flask route using path with leading slash



 MORE:


 ? Python Flask .txt file Encoding
 ? How to % encode single quotes when making jQuery AJAX call?
 ? How to % encode single quotes when making jQuery AJAX call?
 ? How to % encode single quotes when making jQuery AJAX call?
 ? Sqlite3 cannot correctly query a UTF-8 string?
 ? Sqlite3 cannot correctly query a UTF-8 string?
 ? Sqlite3 cannot correctly query a UTF-8 string?
 ? SQLITE UTF-16 Encoding Issues
 ? Comparing same string where one is from Flask and one from a sqlite3 database
 ? python and sqlite3.ProgrammingError on inserting utf-8 string