11

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?

4 Answers 4

7

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:

Sign up to request clarification or add additional context in comments.

Comments

7

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

2 Comments

Is there any way PICO can be used in GAE apps?
After 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.
4

Are you able to execute the script directly from the browser. This looks more like a webserver config issue than jquery's

2 Comments

No, I can't execute it directly. I'm using Apache 2.2. Any ideas what setting I need to alter?
Okay, 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
1

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:

http://webpython.codepoint.net/cgi_tutorial

1 Comment

why is CGI better than mod_python?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.