Run python script with ajax
I have a python script that exports data from a database. script executes exportData () function
I would like to run this on a website by clicking a button via ajax.
This is what I want me to come up with, but it doesn't seem to run the python script.
$(document).ready(function() {
$("#open").click(function(){
$.ajax({
url:"export.py", success: function(){alert("DONE");}
});
});
});
<button type="button" class="open" id="open" onclick="#" >Button</button>
Any help would be much appreciated.
source to share
If you already have an existing website
You cannot directly execute server side python scripts from a webpage (nor can you run client side scripts from a client side). You will need to intercept the server request and then execute its python script.
That is, you need a pipeline that looks like this:
[ client browser ] ----> [ web server ]
[ client browser ] [ web server ] ----> [ python myscript.py ]
[ client browser ] [ web server ] <---- [ python myscript.py ]
[ client browser ] <---- [ web server ]
You can write your own web server software to do this, but if you actually have a python script, CGI is often used to allow users to run "arbitrary" server-side scripts and get stdout
output.
There are different ways to do this depending on your choice of web server, but here is a basic python page that will hopefully give you enough keywords to find a solution that suits your environment. You will find many tutorials if you google for "$ myhttpservername python CGI".
https://docs.python.org/2/howto/webservers.html
Refer to the following tutorial on how to set up pgi-cgi-bin on Apache:
http://www.linux.com/community/blogs/129-servers/757148-configuring-apache2-to-run-python-scripts
If you don't have a web server and just want to use a python script
Another approach would be to create a python script that hosts the web server itself. Cherrypy is one such example . This example shows how to create a web server on port 8080:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!" # or whatever you want to do
index.exposed = True
cherrypy.quickstart(HelloWorld())
source to share