Reputation: 46341
I have a class for a hardware object (here Fridge), and I'd like to automatically create HTTP API routes for a given subset of Fridge's methods, here open
and close
.
from bottle import Bottle, request
class Fridge:
def _not_exposed(self):
print("This one is never called via HTTP")
def open(self, param1=None, param2=None):
print("Open", param1, param2)
def close(self):
print("Close")
# + many other methods
f = Fridge()
app = Bottle("")
for action in ["open", "close"]:
app.route(f"/action/{action}", callback=lambda: (getattr(f, action)(**request.query)))
app.run()
It works, except that in
...callback=lambda: (getattr(f, action)(**request.query))
action
is evaluated when the lambda function is called.
Thus when opening http://127.0.0.1:8080/action/open?param1=123, the lambda is called, and at this time action
has the value ... "close"
(the last value in the for
enumeration), then getattr(f, action)
links to f.close
instead of f.open
. This is not what we want!
Question: in this lambda definition, how to have action
evaluated now, and not postponed?
Expected behaviour for the for
loop:
app.route("/action/open", callback=lambda: f.open(**request.query)))
app.route("/action/close", callback=lambda: f.close(**request.query)))
Upvotes: 3
Views: 46