动态生成Flask路径

2024-05-02 06:04:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从列表中动态生成烧瓶中的路由。我想动态生成视图函数和端点,并用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")

Tags: theaddappurlforindexpage动态
3条回答

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

  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)

不太熟悉烧瓶,所以有可能有一个更干净的方法来做到这一点。(如果对Flask很了解的人认为我的方法天生是错误的,如果他们在评论中解释了原因,我会很乐意删除我的答案。)现在我已经排除了免责声明,下面是我的想法:

app.route("/")是一个decorator函数。@符号只是index = app.route("/")(index)之类的语法糖。因此,你应该能够做这样的事情。。。

routes = [
    ("/", index),
    ("/about", about)
]
for route, view_func in routes:
    view_func = app.route(route)(view_func)

这将允许您从动态创建的路由和函数创建烧瓶路由。

这就是我让它在@This vidor和@PZP下工作的方法,get page方法正在查询sqlite数据库(但它可以是任何数据库),泛型函数def正在循环,在我的实际字典代码列表中,字典也正在从数据库中提取。所以基本上我完成了我需要的。路线是动态的。我可以在sql中打开和关闭路由,而不必去app.py编辑它们。

defaultPage = "/"

@app.route(defaultPage)
def index():
    page = getPage(defaultPage)
    return render_template("index.html", page=page)



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

def generic():
    rule = request.url_rule
    page = getPage(rule)
    return render_template('index.html', page=page)

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)
    )
    app.view_functions[route["func"]] = generic`

相关问题 更多 >