Skip to content Skip to sidebar Skip to footer

Execute Python Script -- Ajax And Flask

I apologize if this is unclear or anything like that. I'm very very new to web programming of any kind, so please be patient. When a link is clicked, I want to run a python script

Solution 1:

There are a few things here that need to be fixed to get things working (or at least how I understand you want them to work).

If you're going to be using Flask, you don't need the route to point to a Python script. You can route to something like /cputemp and then run a function that returns the piece of HTML with the CPU temp that I presume you wanted to display.

@app.route('/cputemp', methods=['GET', 'POST'])defcputemp():
    mytemp1 = commands.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f2 | cut -f1')
    return render_template("cputemp.html", temp=mytemp1)

Don't forget to import commands at the top. Although, you really should be using subprocess instead. https://docs.python.org/2/library/commands.html

The return there uses a Flask template to create the HTML fragment that you want to insert when the AJAX request is successful. http://flask.pocoo.org/docs/0.11/quickstart/#rendering-templates

For example, cputemp.html can simply be something like:

<p>Pi CPU Temp is: {{ temp }}</p>

Note that I don't know whether that command being assigned to mytemp1 works. That's a separate issue from not being able to display the information you want.

Now for the AJAX part. I added an error handler to help debug further issues. Note that I changed the URL to match the route. Also, using innerHTML has security issues, and rather than concerning yourself with sanitizing what you set innerHTML to, use jQuery's html function. http://api.jquery.com/html/

functioncputemp2() {
    $.ajax({
        type: "POST",
        url: "/cputemp",
        dataType: "html",
        success: function(msg) {
            console.log(msg);
            $("#swiss").html(msg);
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });
}

Hope this is enough to get you moving along.

Post a Comment for "Execute Python Script -- Ajax And Flask"