gpt4 book ai didi

python - 动态生成 Flask 路由

转载 作者:太空狗 更新时间:2023-10-30 00:34:51 24 4
gpt4 key购买 nike

我正在尝试从列表动态生成 Flask 中的路由。我想动态生成 View 函数和端点并使用 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")

最佳答案

你有两个可能的解决方案的问题。要么:

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

或者:

  1. 省略 app.add_url_rule 的第三个参数,并将函数分配给 app.view_functions[route["page"]]。代码

     return render_template("index.html")

不是函数。尝试类似的东西

    def my_func():
return render_template("index.html")
# ...
app.view_functions[route["page"]] = my_func

我推荐第一个选项。

来源:the docs .


备选方案:

在 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)

关于python - 动态生成 Flask 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com