(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("
Hello world")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:
$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?
解决方案
I finally managed to do it thanks to the other answer:
Do:
apt-get install libapache2-mod-python
Then create or open the .htaccess file in your website folder, and add
AddHandler mod_python .py
PythonHandler mod_python.publisher
Then create a file test.py:
def index(req):
return("
Hello world")Now accessing www.example.com/test.py works!
NB:
def index(req) is really required: using another name will make it fail.
I don't know why, but it's not possible to set AddHandler mod_python .py in a .htaccess, I only managed to do it globally for a . Does someone have an idea about how to do it directly in the .htaccess?
if mod_python is already installed but not enabled, you have to do:
a2enmod python
service apache2 restart
but this is done automatically when installing libapache2-mod-python.
This is needed in the Apache VirtualHost's Directory: AllowOverride All, Require all granted, to allow handlers to be added directly in a .htaccess file. Without it, an alternative is to add the directives AddHandler ... directly in the VirtualHost definition.