I want to associate a few methods of a (real world) object to Flask URL routes:
class Door:
def __init__(self, location):
pass
def open(self):
pass
def close(self):
pass
def openlater(self, waitseconds=2):
pass
d = Door(location="kitchen")
app.add_url_rule("/door/open", view_func=lambda: d.open())
app.add_url_rule("/door/close", view_func=lambda: d.close())
app.add_url_rule("/door/openlater", view_func=lambda: d.openlater(waitseconds=10))
# or (if we don't override optional parameters):
for func in ['open', 'close', 'openlater']:
app.add_url_rule(f"/door/{func}", view_func=lambda: getattr(d, func)())
But this does not work:
AssertionError: View function mapping is overwriting an existing endpoint function:
How to do this properly with Python Flask?
Note:
I could do
app.add_url_rule(f"/door/{func}", view_func=getattr(d, func))
but then I don't have any lambda
anymore and I cannot set parameters.