1

I have a localhost environment running using Python's SimpleHTTPServer, serving on port 8080.

My project consists of an HTML file, a python script, and a Javascript (vanilla) script.

The method I wish to employ is as follows:

  • Click button in HTML
  • Button fires Javascript AJAX request
  • AJAX request runs Python script
  • Python script produces JSON and returns it to Javascript

My JS is the following:

var json;

function trigger() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        json = xhttp.responseText;
        console.log(json);
    }
  };
  xhttp.open("GET", "./request.py", true);
  xhttp.send();
}

Right now rather than seeing the output of a Python script I'm just seeing the content (as text) of the Python file.

I'm not sure of the correct AJAX call to RUN the .py script rather than just reading it and returning the contents.

Any help would be greatly appreciated!

James B
  • 45
  • 7

3 Answers3

1

SimpleHTTPServer only serves file content. If you want to execute the script and return the output, you need CGIHTTPServer.

Note that both modules have been merged into http.server in python 3.

kthy
  • 827
  • 10
  • 27
0

You need to change the line: xhttp.open("GET", "./request.py", true); to xhttp.open("GET", "http://localhost:3333/<your-route>", true);. <your-route> is defined in your python file and I assume the python web server is running on port 3333.

If you are using Flask and define a route using for example: @app.route("/endpoint"), the request should look like:xhttp.open("GET", "http://localhost:3333/endpoint", true);

Matt
  • 491
  • 3
  • 6
0

You can use SocketServer instead of the default server. Add a handler to the SocketServer. Instead of a GET, do a POST with the actual command to run. The handler can check the post request and run the required script.

grill05
  • 171
  • 14