Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you execute a server-side Python script using jQuery?

I have a very simple Python file, called python1.py, whose contents are:

f = open('C:\\Temp\\test.txt', 'w')
f.write('Succeeded')
f.close()

I wish to execute this from JavaScript, like so:

jQuery.ajax({
   type: "POST",
   url: "/cgi-bin/python1.py",
   success: function (msg) {
       alert("Data Saved: " + msg);
   }
});

However, all that happens is that I get an alert showing me the contents of the Python script. The file C:\Temp\test.txt does not get created, so clearly the Python was not executed.

How do I persuade the code to execute the Python script instead of just reading it?

like image 789
Charles Anderson Avatar asked Feb 04 '10 16:02

Charles Anderson


People also ask

How do I run a Python script in jQuery?

$. ajax({ type: 'POST', url: "scripts/sample.py", data: {param: xyz}, //passing some input here dataType: "text", success: function(response){ output = response; alert(output); } }). done(function(data){ console. log(data); alert(data); });

Can we use jQuery in server side?

No it is not possible to run jQuery on the serverside, as jQuery runs in the users web browser (inside the javascript interpreter) .

How do I run a Python script from server?

Open the file and add the necessary code. NOTE: The file should start with the path to the Python scripts that is /usr/bin/python on our servers, but you can run the whereis python command via SSH to check the directory. To save the changes, click Crtl+O and press Enter for Windows or Command+O for Mac OS.

Can jQuery be used with Python?

To get started with PyQuery , install the Python package using PIP. Once you have installed PyQuery , import it into the Python program. Pass the input XML to the PyQuery object and you should be able to apply jQuery style queries to it. Assume divMain as a jQuery object and print the HTML content of the div.


1 Answers

You simply need to configure your web server to execute your *.py scripts, instead of serving them as plain text.

If you are using Apache as a web server, you need to enable mod_python or mod_wsgi.


EDIT:

Since you are using using Apache, you may want to check the following article, which briefly describes how to set up the mod_python module:

  • A Brief Introduction to Apache's mod_python Module
like image 183
Daniel Vassallo Avatar answered Oct 05 '22 03:10

Daniel Vassallo