Thursday, 2 January 2020

How to let the webserver (e.g. Apache) call Python directly?

(Important) Disclaimer: I know it's probably not a good idea, that Python is not like PHP, and that the "natural" way to do web with Python is more by using a framework like Bottle, Flask, Django (that I already use), etc. But still, just out of curiosity, I'd like to see how the following is possible.


When Apache + PHP are installed, we can access a page like http://www.example.com/index.php. Internally, Apache probably passes the request to PHP which executes code, produces a text output, which is then served by Apache.

Question: how could we do something similar in Python? i.e. by accessing http://www.example.com/index.py, Apache would call the script index.py:

print("<html><body>Hello world</body></html>")

and then Apache would serve this page to the client.


NB:

  • Calling http://www.example.com/index.py?foo=bar could even give the params to the Python script in sys.argv

  • I already did it like this: http://www.example.com/index.php:

    <?php 
    $out = shell_exec("python index.py"); 
    echo($out); 
    ?>
    

    which then calls the Python script and produces the output. It works, but I'd like to do it without PHP.

  • Said in another way, is there something like mod_php for Python?



from How to let the webserver (e.g. Apache) call Python directly?

No comments:

Post a Comment