动态生成Flask路线

Jes*_*sse 5 python flask

我试图从列表中动态生成Flask中的路由.我想动态生成视图函数和端点并添加它们add_url_rule.

这是我想要做的,但我得到一个"映射覆盖"错误:

routes = [
    dict(route="/", func="index", page="index"),
    dict(route="/about", func="about", page="about")
]

for route in routes:
    app.add_url_rule(
        route["route"], #I believe this is the actual url
        route["page"], # this is the name used for url_for (from the docs)
        route["func"]
    )
    app.view_functions[route["func"]] = return render_template("index.html")
Run Code Online (Sandbox Code Playgroud)

A. *_*dor 7

两个可能的解决方案有一个问题.或者:

  1. route[func]直接引用函数,而不是字符串.在这种情况下,您不必分配任何内容app.view_functions.

要么:

  1. 省略第三个参数app.add_url_rule,并为其分配一个函数app.view_functions[route["page"]].代码

    return render_template("index.html")
    
    Run Code Online (Sandbox Code Playgroud)

    不是一个功能.尝试类似的东西

    def my_func():
        return render_template("index.html")
    # ...
    app.view_functions[route["page"]] = my_func
    
    Run Code Online (Sandbox Code Playgroud)

我推荐第一个选项.

资料来源:文档.


替代解决方案:

在URL中使用可变部分.像这样的东西:

@app.route('/<page>')
def index(page):
  if page=='about':
     return render_template('about.html') # for example
  else:
     some_value = do_something_with_page(page) # for example
     return render_template('index.html', my_param=some_value)
Run Code Online (Sandbox Code Playgroud)


pzp*_*pzp 5

不太熟悉Flask,所以有可能有更简洁的方法来做到这一点.(如果对Flask有所了解的人认为我的方法本质上是错误的,我会很乐意删除我的答案,如果他们在评论中解释为什么.)现在我已经取消了免责声明,这是我的想法:

app.route("/")是一个装饰功能.这种@表示法只是类似于语法的糖index = app.route("/")(index).因此,你应该可以做这样的事......

routes = [
    ("/", index),
    ("/about", about)
]
for route, view_func in routes:
    view_func = app.route(route)(view_func)
Run Code Online (Sandbox Code Playgroud)

这将允许您从动态创建的路线和功能创建Flask路线.