动态生成Flask路线 [英] Dynamically generate Flask routes

查看:53
本文介绍了动态生成Flask路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to dynamically generate routes in Flask from a list. I want to dynamically generate view functions and endpoints and add them with add_url_rule.

这是我要尝试执行的操作,但是出现映射覆盖"错误:

This is what I am trying to do but I get a "mapping overwrite" error:

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

推荐答案

您可能会遇到两种解决方案.要么

You have one problem with two possible solutions. Either:

  1. 具有route[func]直接引用一个函数,而不是字符串.在这种情况下,您无需为app.view_functions分配任何内容.
  1. Have route[func] directly reference a function, not a string. In this case, you don't have to assign anything to app.view_functions.

或者:

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

  1. Leave out the third argument of app.add_url_rule, and assign a function to app.view_functions[route["page"]]. The code

return render_template("index.html")

不是功能.尝试类似

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

我建议第一种选择.

来源:文档.

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

Use variable parts in the URL. Something like this:

@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路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆