Taking form button input
Question: So i'm using Flask to build a basic control panel for an IR Automation in my
home. However I'm failing to understand how to take a response from the form
in my HTML. So I basically have a button that changes the state of a device
when pressed. The issue I'm having is taking that response and updating it on
the HTML page to say it's on or off.

My python flask code:

    
    
    if request.method == 'POST':
            if request.form['lamp'] == 'on':
                btn1 = True
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((IP, PORT))
                s.send(MSG.encode())
                data = str(s.recv(BUFFER).decode())
                print(data)
                s.close()
    
            elif request.form['lamp'] == 'off':
                btn1 = False
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.connect((IP, PORT))
                s.send(MSG.encode())
                data = str(s.recv(BUFFER).decode())
                print(data)
                s.close()
    

And the HTML part it works with:

    
    
                    <form method=post>
                        {%  if btn1 == True  %}
                            <button type=submit class="btn btn-default" name="lamp" value="on"><i class="fa fa-lightbulb-o fa-5x" style="color:yellow;"></i><br>Lamp</button>
                            {{  btn1  }}
                        {% else %}
                            <button type=submit class="btn btn-default" name="lamp" value="off"><i class="fa fa-lightbulb-o fa-5x"></i><br>Lamp</button>
                            {{  btn1  }}
                        {%  endif  %}
                    </form>
    

Why isn't btn1's state changing when I click it?

Thanks, James


Answer: really you should probably just be using json calls

**flaskapp.py**

    
    
    from flask import Flask,render_template
    import json
    app = Flask(__name__)
    def load_data(flat_file):
        try:
            return json.load(open(flat_file))
        except (IOError,ValueError):
            return {}
    db_file = "my_data.json"
    
    @app.route("/lamp/on")
    def lamp_on():
        data = load_data(db_file)
        data["lamp"] = "on"
        json.dump(data,open(db_file,"wb"))
        return json.dumps(data)
    
    @app.route("/lamp/off")
    def lamp_off():
        data = load_data(db_file)
        data["lamp"] = "off"
        json.dump(data,open(db_file,"wb"))
        return json.dumps(data)
    
    @app.route("/status")
    def status():
        return load_data(db_file).get("lamp","off")
    @app.route("/")
    def main():
        return render_template("template.html")
    
    if __name__ == "__main__":
        app.run(debug=True)
    

this app will provide an api to turn on and off the light (obviously you will
want to do more than just write to a file). as well as a visual dashboard at
the "/" route

**template.html**

    
    
    <head>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    </head>
    <body>
    <div id="content">
    
    </div>
    </body>
    <script>
        function OnButton(){
            var url = "/lamp/"+$("#lamp_btn").val().toLowerCase()
            $.get(url,update_button)
        }
        function update_button(){
            $.get("/status",function($data){
                var next_state = $data == "off"? "On":"Off"
                var button = $('<button id="lamp_btn" value="'+next_state+'">Turn Lamp '+next_state+'</button>')
                button.click(OnButton);
                $("#content").html(button)
            });
        }
        update_button();
    </script>
    

this is the dashboard it just uses json calls to the api and updates just the
button (but you could update much more... this is just a very simple example)

