With just installing the package libapache2-mod-python you’re not done yet. I tried to get it working but it turned out that I had to adapt the configuration files by myself. This is not how it should be in my eyes, since beginning Ubuntu users will have a hard time to get it working. Anyway, I’m going to file a bug after this post has been post.
I based my guide on the official mod_python documentation, which can be found here: Mod_python Manual.
The first step was to let apache send .py files to the python module to parse them. This is done by adding this following code to /etc/apache2/sites-available/default.
AddHandler mod_python .py
Add this before </Directory> in the <Directory ></Directory> structure of the directory you want to enable python in. Make sure you restart apache now.
Now you want to execute some python code. This isn’t the same as with PHP. You can’t just write print “Hello World” and the browser will display Hello World. The handler works with different modules. You have to define in your file and request it with your URI. I’ll show you this with the example code from the documentation. Paste this in a file and save it as test.py:
#!/usr/bin/python """ Publisher example """ def say(req, what="NOTHING"): return "I am saying %s" % what
This code defines the module say. You can execute it by going to http://localhost/test.py/say if you’ve saved it in your server root. You probably already saw the variable what, which is passed on. This variable can be passed on in this way: http://localhost/test.py/say?what=hi
The module name for the default one, if no module name is passed on is index. http://localhost/test.py will look for the module index and if that isn’t present it will return a 404 error. Please make sure you pass req on in every definition of a module. Note that if a non-existing module is requested a 404 error will be sent to the browser.
A note: Apache is restarted with sudo apache2 -k restart. If that doesn’t work for you, you can try it with sudo dpkg-reconfigure apache2-mpm-prefork.
If you find any errors in this blog post or think that certain things are incomplete or can be done better, please don’t hestitate to tell me. I’m not that experienced with python. 😉