python - Flask 路由规则作为函数参数

标签 python flask

<分区>

我想以路径的形式为路由指定任意数量的参数:/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 路由规则作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31162560/

相关文章:

python - 在 mac 10.8.5 上安装 pycurl 时遇到问题

python - 在同一 Tensorflow session 中从 Saver 加载两个模型

python - 在 PyQt4 中显示视频流的最佳方式是什么?

python - 子列表的唯一元素取决于子列表中的特定值

python - Flask-HTTPAuth verify_password 函数未收到用户名或密码

python - 从 flask rest API 返回 jsonify() 和返回 make_response 有什么区别?

python - 多个 Bokeh 服务器集成到 Flask

python - 使用 GraphQL 和 Graphene-Python 从数据库中选择仅请求的字段

docker - 简单的 flask 服务在 docker 容器外不响应

python - 如何在 Flask 中制作 RadioField?