alex j alex j - 5 months ago 73
Python Question

calling python function from html button to run shell command

What I am trying to do is call a function from the python script I have defined to run a simple gpio shell command.

I don't need it to return or go anywhere, just run the command and stay on the page.

Here is what I have.

from flask import Flask, render_template
import subprocess

app = Flask(__name__)

def index():
return render_template('index.html')

def main():
return render_template('main.html')

#setup calls for hardware to set state['./'])

def pin0on():['gpio write 0 1'])

def pin0off():['gpio write 0 0'])

I have been trying to call it with {{ pin0on }} or off.

The page with the buttons is main.html with just a simple page with two buttons. I am using href to call it. I can't seem to find anything along these lines anywhere. Or I may be just doing this wrong.

Answer Source

You have to put the code in a view function:

def turn_on():['gpio write 0 1'], shell=True)
    return '', 204  # no content

Then in the template, the button will like this:

<a href="{{ url_for('turn_on') }}">Turn on</a>

When the button was clicked, it will trigger the turn_on view function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download