Friday, 30 May 2014

Getting Started:Python-CGI programming Configuring CGI scripts on apache server

Before starting Python-CGI programming first we have to allow apache server to run CGI scripts.
The following steps are for ubuntu 14.04 users:


Step 1:Using ScriptAlias

Open terminal and run 

sudo gedit /etc/apache2/apache2.conf
Note:First create the following directory /var/www/cgi-bin

Add the following lines:-

ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py

ScriptAlias converts /cgi-bin/ address to the specified address.
The following AddHandler directive tells the server to treat all files with the cgi or pl extension as CGI programs.

Open terminal and run 

sudo gedit /etc/apache2/conf-available/serve-cgi-bin.conf
Add the following lines between <IfDefine ENABLE_USR_LIB_CGI_BIN> and </Directory>
.

ScriptAlias /cgi-bin/ /var/www/cgi-bin
   
      Options +ExecCGI

Step 2 :Creating CGI scripts

Open terminal and run 


sudo gedit /var/www/cgi-gin/hello.py

Copy the following lines and save the file.

#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

'Note: /usr/bin/python is the python installation directory

After saving the file then run the following command:

chmod +x hello.py

Now restart the apache server:

sudo /etc/init.d/apache2 restart


Step 3 :Running CGI scripts

Now open your browser and type the url


localhost/cgi-bin/hello.py



It will print Hello World! This is my first CGI program.