Capture arbitrary path in Flask route
Use the path
converter to capture arbitrary length paths: <path:path>
will capture a path and pass it to the path
argument. The default converter captures a single string but stops at slashes, which is why your first url matched but the second didn't.
If you also want to match the root directory (a leading slash and empty path), you can add another rule that sets a default value for the path argument.
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_dir(path):
return path
There are other built-in converters such as int
and float
, and it's possible to write your own as well for more complex cases.
Darwin Tech
Updated on August 09, 2020Comments
-
Darwin Tech over 3 years
I have a simple Flask route that I want to capture a path to a file. If I use
<path>
in the rule, it works for/get_dir/one
but not/get_dir/one/two
. How can I capture an arbitrary path, so thatpath='/one/two/etc
will be passed to the view function?@app.route('/get_dir/<path>') def get_dir(path): return path
-
FrEaKmAn about 6 yearsFor those that <path:path> is not working, make sure you remove static_url_path, github.com/pallets/flask/issues/1633
-
Bob Stein over 5 yearsI'm a little spooked that you have to add another rule for the root. Is it simply understood that variable parts cannot be the empty string?
-
kungphu almost 5 years@BobStein I'm late to the party, but note that the source for werkzeug.routing.PathConverter defines the regex for matching paths as
[^/].*?
. The[^/]
at the beginning means it requires at least one non-slash character, with any other characters (including slashes) optionally occurring after that. I'd expect that behavior, if only because an 'index page' is a pretty common concept and matching the empty string in a URL isn't a behavior I've ever seen (or wanted). -
Sohail Saha almost 3 yearsThanks a lot. 'path' is exactly what I needed.
-
djcunningham0 over 2 yearsTo be clear, the first 'path' in
<path:path>
is the converter and the second one is the value being passed in. So you would write@app.route('/<path:my_path>')
if named your parameter my_path.