Capture arbitrary path in Flask route


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 that path='/one/two/etc will be passed to the view function?

def get_dir(path):
    return path
10/22/2015 5:23:22 PM

Accepted Answer

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': ''})
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.

8/8/2018 2:57:07 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow