在 Flask 路由中捕获任意路径 [英] Capture arbitrary path in Flask route
问题描述
我有一个简单的 Flask 路由,我想捕获文件的路径.如果我在规则中使用
,它适用于 /get_dir/one
但不适用于 /get_dir/one/two
.如何捕获任意路径,以便将 path='/one/two/etc
传递给视图函数?
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
推荐答案
使用 path
转换器捕获任意长度的路径:
将捕获一个path 并将其传递给 path
参数.默认转换器捕获单个字符串但在斜杠处停止,这就是为什么您的第一个 url 匹配但第二个不匹配的原因.
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
还有其他内置转换器,例如int
和 float
,并且可以编写您的 也适用于更复杂的情况.
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.
这篇关于在 Flask 路由中捕获任意路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!