Create HTML button to run Python Script

2019-01-25 22:53发布

问题:

So I have been searching for this answer for a while, and most answers that I have found are either to vague, or above my knowledge with programming.

What I am trying to do is 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 in order to accomplish this however everytime I try something it doesnt work. Would anybody be able to help me?

Thank you!

回答1:

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