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
.
You have one problem with two possible solutions. Either:
route[func]
directly reference a function, not a string. In this case, you don't have to assign anything to app.view_functions
.Or:
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.
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)