Skip to content Skip to sidebar Skip to footer

Flask Button Run Python Without Refreshing Page?

I am just getting started into python and flask (for the raspberry pi). I want a web application that would execute some python code to pan and tilt a camera and display a video st

Solution 1:

I would split it out into two routes to make it easier to see what you have to do:

LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"
AVAILABLE_COMMANDS = {
    'Left': LEFT,
    'Right': RIGHT,
    'Up': UP,
    'Down': DOWN,
    'Reset': RESET
}

@app.route('/')defexecute():
    return render_template('main.html', commands=AVAILABLE_COMMANDS)

@app.route('/<cmd>')defcommand(cmd=None):
    if cmd == RESET:
       camera_command = "X"
       response = "Resetting ..."else:
        camera_command = cmd[0].upper()
        response = "Moving {}".format(cmd.capitalize())

    # ser.write(camera_command)return response, 200, {'Content-Type': 'text/plain'}

Then in your template you just need to use some JavaScript to send off the request:

{# in main.html #}
{% for label, command in commands.items() %}
    <buttonclass="command command-{{ command }}"value="{{ command }}">
        {{ label }}
    </button>
{% endfor %}

{# and then elsewhere #}
<script>// Only run what comes next *after* the page has loadedaddEventListener("DOMContentLoaded", function() {
  // Grab all of the elements with a class of command// (which all of the buttons we just created have)var commandButtons = document.querySelectorAll(".command");
  for (var i=0, l=commandButtons.length; i<l; i++) {
    var button = commandButtons[i];
    // For each button, listen for the "click" event
    button.addEventListener("click", function(e) {
      // When a click happens, stop the button// from submitting our form (if we have one)
      e.preventDefault();

      var clickedButton = e.target;
      var command = clickedButton.value;

      // Now we need to send the data to our server// without reloading the page - this is the domain of// AJAX (Asynchronous JavaScript And XML)// We will create a new request object// and set up a handler for the responsevar request = newXMLHttpRequest();
      request.onload = function() {
          // We could do more interesting things with the response// or, we could ignore it entirelyalert(request.responseText);
      };
      // We point the request at the appropriate command
      request.open("GET", "/" + command, true);
      // and then we send it off
      request.send();
    });
  }
}, true);
</script>

Solution 2:

I've got the same problem, and the answer is simple using ajax XmlHttpRequest:

// send a request, but don't refresh page
xhttp = newXMLHttpRequest();
xhttp.open("GET", "your script action", true);
xhttp.send();

Here's a small example, calling current script with parameters "like", embedded in a function:

function likeStuffs()
{
    // send a request, but don't refresh page
    xhttp = new XMLHttpRequest();
    xhttp.open("GET", "?like", true);
    xhttp.send();
}

Solution 3:

You can simply do this with help of AJAX... Here is a example which calls a python function which prints hello without redirecting or refreshing the page.

In app.py put below code segment.

//rendering the HTML page which has the button@app.route('/json')
def json():
    return render_template('json.html')

//background process happening without any refreshing@app.route('/background_process_test')
def background_process_test():
    print "Hello"
    return "nothing"

And your json.html page should look like below.

<scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><scripttype=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
        returnfalse;
      });
    });
</script>


//button
<divclass='container'><h3>Test</h3><form><ahref=#id=test><buttonclass='btn btn-default'>Test</button></a></form></div>

Here when you press the button Test simple in the console you can see "Hello" is displaying without any refreshing.

Post a Comment for "Flask Button Run Python Without Refreshing Page?"