I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python SimpleHTTPServer.SimpleHTTPRequestHandler?
A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. here), but so far I could not come up with a truly minimal one.
In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction – so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).
O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions.
the python server file:
…and the HTML file (I call it ‘frontend.html’, unfortunately the name has to appear in the JavaScript code as well):
Of course it would be much more convenient to use jQuery for the XML request, but in the interest of simplicity I’ll leave it like that.
Finally an alternative implementation using WSGI (unfortunately I didn’t see a way to fall back on the standard file-serving handler if the request is not a POST):