Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

@app.route('/get_dir/<path>') def get_dir(path):     return path 
like image 782
Darwin Tech Avatar asked Feb 27 '13 16:02

Darwin Tech


People also ask

Can you use multiple decorators to route URLs to a function in flask?

We can use multiple decorators by stacking them.

What is the default route request in flask?

By default, a route only answers to GET requests. You can use the methods argument of the route() decorator to handle different HTTP methods. If GET is present, Flask automatically adds support for the HEAD method and handles HEAD requests according to the HTTP RFC.


1 Answers

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.

like image 154
moodh Avatar answered Oct 12 '22 02:10

moodh