Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

python - 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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...