This question already has an answer here:
Match an arbitrary path, or the empty string, without adding multiple Flask route decorators
                                
                                    (1个答案)
                                
                        
                                去年关闭。
            
                    
我想以路径的形式指定任意数量的参数到路由:/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。这就是我们拆分它的原因。

关于python - flask 路线规则作为函数args ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31162560/

10-12 22:02