Building a PHP script that responds to an Ajax request is as easy as:
<?php
$command = $_POST["command"];
if ($command == "say_hello") {
$name = $_POST["name"];
echo json_encode(array("message" => "Hello, " . $name));
}
?>
and, at least if you’re using jQuery on the client side, and if you specified a callback function on the original request, the array containing the message will be passed into that callback function.
But with Python it’s not that simple. Or at least I haven’t figured out how to make it that simple. If I just try to “print” a response (paralleling PHP’s “echo” statement above) the client doesn’t get anything back.
Whenever I’ve looked on the internet for how to respond to an Ajax request with Python, the answer always involves using Django or some other web framework.
And I know those things are great, but what is PHP doing that makes using a similar package unnecessary? I would like to be writing my server-side script in Python instead of PHP, but I’d prefer a D.I.Y. approach to using a third-party framework for what should be (right?) a pretty simple task.
Any help? An example of how to do this would be much appreciated.
I might have some of the details wrong, but I’ll try to explain why this is the case. Firstly, the PHP you’re talking about is baked directly into the apache webserver. When you do an
echo, it outputs the result to the response stream (a TCP connection between the server and client). When you doprintin python, what you’re doing is outputting the result to standard out (the command line).How most languages work with the web, is that a request comes in to some kind of web server, and that web server executes a program. The program is responsible for returning a stream, which the webserver takes, and streams to the client over the TCP connection.
I’m assuming that the webserver redirects PHPs standard out to the webservers stream, and that is how PHP is able to use
echoto return its result. This is the exception, not the rule.So, to use python to serve requests, you need to have a webserver that can execute python in some way. This is traditionally done using CGI. More recently, something like
mod_pythonwas used to host the python within apache. Nowadays,wsgiormod_wsgiis used, which is the standard defined for webservers talking to python.You might want to look at something like web.py, which is a minimalist python web framework. This will get you very very close to what you’re trying to do.