Jesse Jesse - 4 months ago 11
Python Question

Dynamically generate Flask routes

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

Answer

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('/<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)