Apparently, Flask’s app.route / app.add_url_rule doesn’t work with closures. For example, creating a basic app with,
for name in ('/hi', '/bye'):
app.add_url_rule(name, view_func=lambda: name)
and querying it,
dev:~/pg/yelp-main> curl localhost:9113/hi
/bye
shows that it doesn’t work with closures. What’s the easiest way to work around this? Can I force Python to actually create two functions?
You haven’t actually created a closure in your code that preserves the value of
name:To preserve the value you need to pass the value into the closure:
EDIT: In addition, you’ll need to ensure that each time you register a function using
add_url_ruleyou either specify anendpointor ensure each function has a unique__name__(since Flask actually stores the routes in a dictionary keyed on theendpoint, which it derives from the function’s__name__if no other is provided). Otherwise, your second view will overwrite your first one.You may want to look into Flask’s class-based Views – they may make it easier to build the dynamics you are looking for (although closures and classes are quite similar [in that both are the poor man’s substitute for the other]).