python - 动态生成 Flask 路由

标签 python flask

我正在尝试从列表动态生成 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/

相关文章:

python - 使用无服务器框架将库/依赖项注入(inject) AWS Lambda

python - python中,如果os.chdir = 'path'已经实现,如何恢复os.chdir()的功能

python - 获取范围 0 - 2*pi - python

python - is_authenticated() 引发 TypeError TypeError : 'bool' object is not callable

python - 获取格式错误的 url route-flask

python - 部署 ARM 模板时出错。找不到与模板文件模式匹配的任何文件

python - JSON 和 MySQL 更新查询

python - 方法是否用类实例化,消耗大量内存(在 Scala 中)?

python - 如何在 Flask + Gunicorn 应用程序中使用后台调度程序

Python Flask mod-wsgi 自定义 header 不在请求中