I have the following setup
LEDS = {"green": 16, "red": 18}
@app.route('/leds/', methods=["GET"])
def api_leds_state():
return {"green": GPIO.input(LEDS["green"]), "red": GPIO.input(LEDS["red"])}
which returns the pins state
{
"green": 0,
"red": 0
}
Unfortunately the code above is hardcoded. How can i get the desired json response with a loop or serialization or something?
Not exactly sure that's what you're asking for, but here's a dictionary comprehension to overcome the hardcoded keys in your return dict:
return {color:GPIO.input(pin) for color, pin in LEDS.items()}
Iterating over LEDS.items()
gives you both the key and value of a pair in LEDS
, which is what you need to create each new pair in your result dict.