Create HTML button to run Python Script

user2125116 picture user2125116 · Mar 1, 2013 · Viewed 31.6k times · Source

I am trying to create a button on a webpage quad_relay.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o$
<html xmlns="http://www.w3.org/1999/xhtml">
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
 <body>
   <h1>Quad Web Relay</h1>
   <div>Relay 1:
     <input type="button" value="Toggle" id="toggle1" />
   </div>
 </body>
</head>
</html>

When that button is clicked I want it to run a python script set_gpio.py

def set_pins_high():
        fp = open("/sys/class/gpio/gpio"+pin+"/value","w")
        fp.write(str(1))
        fp.close()
def set_pins_low():
        fp1 = open("/sys/class/gpio/gpio"+pin+"/value","w")
        fp1.write(str(0))
        fp1.close()

for pin in pins:
        for x in range (0,2):
                set_pins_high()
                time.sleep(0.5)
                set_pins_low()
                time.sleep(0.5)

The webpage is located on a lighttpd server running Django. I have jQuery and AJAX installed, and I know they are the route that I need to take to accomplish this however everytime I try something it doesnt work.

Answer

Fernando Freitas Alves picture Fernando Freitas Alves · Mar 2, 2013

you have to do some modifications:

In your HTML file:

<div>Relay 1:
  <form action= '{% url my_view_name%}' method="POST">
      <input type="submit" value="Toggle" id="toggle1" />
  </form>
</div>

in urls.py

url(r'whatever^$', 'core.views.my_view',name='my_view_name'),

In views.py:

def my_view(request):
    if request.method == 'POST':
        import set_gpio
        #Do your stuff ,calling whatever you want from set_gpio.py

    return #Something, normally a HTTPResponse, using django