lengi
lengi

Reputation: 3

Control .py with Flask and Buttons

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")

Upvotes: 0

Views: 2510

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599590

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

Upvotes: 4

Related Questions