How do you execute a server-side Python script using jQuery?
Solution 1
Are you able to execute the script directly from the browser. This looks more like a webserver config issue than jquery's
Solution 2
You could also use the opensource project Pico. It's a really elegant way of calling server side Python code from client side Javascript.
The author has provided some simple examples here https://github.com/fergalwalsh/pico/wiki/Example-1:-Hello-World
Solution 3
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:
Solution 4
If your script is that simple, you would be best off using CGI on the server side rather than mod_python or mod_wsgi as suggested by others. For details on how to set up Apache for CGI with Python and simple script examples see:
Charles Anderson
40 years or so as a professional software engineer, working in computer-aided design, petrochemical automation, semiconductor manufacturing, and data management. Most recent experience in JavaScript / Node.js, Python, HTML/CSS, and C++. Also Git, Mercurial, Jenkins, JIRA/Crucible, Less, Stylus, XML, UML. Now retired!
Updated on August 17, 2020Comments
-
Charles Anderson almost 4 years
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?
-
Charles Anderson over 14 yearsNo, I can't execute it directly. I'm using Apache 2.2. Any ideas what setting I need to alter?
-
Charles Anderson over 14 yearsOkay, I've found the mistake: I used Alias in my httpd.conf file instead of ScriptAlias. I'm now returning the output of the Python file, but it still won't create the temp file. I will leave that to another question
-
lynxoid over 11 yearswhy is CGI better than mod_python?
-
Simon K Bhatta4ya over 10 yearsIs there any way PICO can be used in GAE apps?
-
Evan R about 10 yearsAfter many headaches trying to get Apache and mod_python to work, I (luckily) stumbled across this post, where I was able to get my JS and Python talking to each other in no time flat. Pico rocks! Extremely easy to set up and implement.