Sunday, May 19, 2013

Installing mod_python in Apache2

mod_python is an Apache module to embed Python within your server. The steps to install it on Ubuntu and create a simple "Hello, world" page are the following ones:


Install mod_python

On Ubuntu, it is as simple as running:
$ sudo apt-get install libapache2-mod-python

Configure a new virtual host

I suggest to use a new virtual host instead of the default one. To do so, create a new file called test in the directory /etc/apache2/sites-available/ with the following content:

<VirtualHost *:80>
     ServerAdmin webmaster@localhost
     DocumentRoot /var/www/test/web/
     ErrorLog /var/www/test/logs/error.log
     CustomLog /var/www/test/logs/access.log combined

     <Directory /var/www/test/web/>
          Options Indexes FollowSymLinks MultiViews
          AllowOverride None
          Order allow,deny
          allow from all
          AddHandler mod_python .py
          PythonHandler mod_python.publisher
          PythonDebug On
     </Directory>
</VirtualHost>

And then create the directories /var/www/test/web/ and /var/www/test/web/logs. Now you can enable the new virtual host:

$ sudo a2dissite default
$ sudo service apache2 reload
$ sudo a2ensite test
$ sudo service apache2 restart

Create a "Hello, world" page

Create a file in /var/www/test/web/ with the name hello.py and write the following function:
def index(req):
    req.content_type = "text/html"
    return "<h1>Hello, world!</h1>"
Finally, open http://localhost/hello and it will show you a welcoming h1 element.

No comments:

Post a Comment