我想以路径的形式为路由指定任意数量的参数:/arg/arg2/arg3/etc
。我无法弄清楚如何在单个函数中的路由下捕获所有这些“子路由”。我怎样才能使它工作?
from flask import Flask
app = Flask("Example")
@app.route("/test/<command>/*")
def test(command=None, *args):
return "{0}: {1}".format(command, args)
app.run()
预期行为是:
/test/say
-> say: ()
/test/say/
-> say: ()
/test/say/hello
-> say: ("hello",)
/test/say/hello/to/you
-> say: ("hello", "to", "you")
我不确定你是否可以按照你喜欢的方式接受多个参数。
实现此目的的一种方法是定义多个路由。
@app.route('/test/<command>')
@app.route('/test/<command>/<arg1>')
@app.route('/test/<command>/<arg1>/<arg2>')
def test(command=None, arg1=None, arg2=None):
a = [arg1, arg2]
# Remove any args that are None
args = [arg for arg in a if arg is not None]
if command == "say":
return ' '.join(args)
else:
return "Unknown Command"
http://127.0.0.1/test/say/hello/
应该返回 hello
http://127.0.0.1/test/say/hello/there
应该返回 hello there
另一种方法是使用path
:
@app.route('/test/<command>/<path:path>')
def test(command, path):
args = path.split('/')
return " ".join(args)
如果你使用这个,那么如果你去http://127.0.0.1/test/say/hello/there
。
然后 path
将被设置为值 hello/there
。这就是我们拆分它的原因。