我正在尝试从列表动态生成 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")
最佳答案
你有两个可能的解决方案的问题。要么:
- 让
route[func]
直接引用函数,而不是字符串。在这种情况下,您不必为app.view_functions
分配任何内容。
或者:
省略
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/