0

What is necessary to get a button on a webpage work with flask? I just want to turn a LED on.

the html looks like:

<tr>
  <td><h3>Computer</h3></td>
  <td><p><input type="submit" name="btnled" value="ON"></p></td>
  <td><p><input type="submit" name="btnled" value="OFF"></p></td>
</tr>

How can i catch the pressed button in python to turn the led on? What do i need? WTForms?

Edit:

the .py looks like this:

from flask import request
@app.route("/switch_led", methods=['POST'])
def led_handler():
    if request.form['btnled'] == "ON":
        print("ON")
    elif request.form['btnled'] == "OFF":
        print("OFF")

1 Answer 1

4

No need for a forms framework for something so simple.

You need to wrap the buttons in a form element, with an action pointing at your handler URL:

<form action="/switch_led" method="POST">
  <p><input type="submit" name="btnled" value="ON"></p>
  <p><input type="submit" name="btnled" value="OFF"></p>
</form>

And in the handler class:

from flask import request

@app.route('/switch_led', methods=['POST'])
def led_handler():
    if request.form['btnled'] == "ON":
        # do ON action
    elif request.form['btnled'] == "OFF":
        # do OFF action
Sign up to request clarification or add additional context in comments.

6 Comments

I only get this when i run the .py file and click on the button: 192.168.178.65 - - [01/Apr/2014 14:18:58] "GET /?btnled=ON HTTP/1.1" 200 - 192.168.178.65 - - [01/Apr/2014 14:18:58] "GET /home HTTP/1.1" 200 -
Then your template is wrong, as that is clearly a GET request and the template I show above has a POST, and it is requesting / rather than /switch_led.
you're right! i forgot to delete a old form. I get POST now but there is a new problem. When i click on the button, i get the error page with the error ValueError: View function did not return a response. Is this because i only have a print("ON") in my if function?
Yes, your view always needs to return a response, even if it's just return 'ON'.
Is there no way to avoid this? When i insert the return 'ON', it opens a new blank page just saying "ON" but i don't want to change the site because i can't see all of my buttons anymore. I tried to retrun the html with the buttons and it works, but i want to load the html a second time. Is there a way to return anything that really nothing happens on my webpage?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.