Dynamically generate Flask routes

前端 未结 3 1054
渐次进展
渐次进展 2021-01-05 10:50

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.

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 11:46

    You have one problem with two possible solutions. Either:

    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.

    Or:

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

      is not a function. Try something like

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

    I'd recommend the first option.

    Source: the docs.


    Alternate solution:

    Use variable parts in the URL. Something like this:

    @app.route('/')
    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)
    

提交回复
热议问题