在Flask路径中捕获任意路径 [英] Capture arbitrary path in Flask route
问题描述
我有一个简单的Flask路由,我想捕获一个文件的路径。如果我在规则中使用< path>
,它适用于 / get_dir / one
但不是 / get_dir /一/二
。如何捕获一个任意路径,以便 path ='/ one / two / etc
将被传递给视图函数?
@ app.route('/ get_dir /< path>)
def get_dir(路径):
返回路径
路径
捕获任意长度的路径:< path:path>
将捕获一个路径并将其传递给路径
参数。默认转换器捕获一个字符串,但停止在斜线,这就是为什么你的第一个url匹配,但第二个没有。 如果你还想匹配的根目录(一个主要的斜杠和空路径),你可以添加另一个规则,设置一个默认值
$ $ p $
@ app.route('/',defaults = {'path':''})
@ app.route('/< path:path>')
def get_dir(路径):
返回路径
还有其他内置转换器作为 int
和 float
,可以编写自己的以及更复杂的情况下。
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
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.
这篇关于在Flask路径中捕获任意路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!