TCP/IP
Today i started to learn python cgi. In the begining, i had to know the network concepts like how data are transferred over the network. I got clear idea about TCP/IP(Transmission Control Protocol/Internet Protocol), that is, It is a rule to be followed for transferring data over internet. First data are divided into small packets and packed with relevant information and IP assigns destination address to each packets
Now all packets are no need to follow the same path. Router will direct the packets to manage data traffics over internet to reach its destination.
And there are different type of HTTP requests GET, POST, PUT, CONNECT, TRACE, DELETE, HEAD, OPTIONS.
CGI – Common Gateway Interface
It is external program to a web server which process the client requests and return respective results.
CGI Concept and Processing Steps :
1. Client sends requests
2. Server receives requests
3. Contacting external program called CGI script
4. CGI script process client data and returns the result to server
5. Server serves response to Client
It can be written in Ruby, Python, PHP, Perl. CGI mostly uses GET and POST.
I got tired to configure the apache server to make working python file. Finally, i succeeded to work with python cgi.
These are all the steps which i did,
First i created folders /var/www/python/cgi-bin/ and changed folder permission
as $ sudo chmod -R 777 /var/www/python
Then i created this test file to check in the browser and saved it as index.py in cgi-bin folder
#!/usr/bin/python
print “Content-Type: text/plain\n\n”
print ‘python works’
And i added the cgi-bin directory path in /etc/apache2/httpd.conf file as follows:
<Directory “/var/www/python/cgi-bin”>
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory “/var/www/python/cgi-bin”>
Options All
</Directory>
If cgi-bin directory path is not set, apache will throw 403 Forbidden error, that means, either you dont have enough permission or this folder is not having 777 permission. Next is, restarting apache server sudo /etc/init.d/apache2 restart to reflect the changes in server.
Now i tested the index.py file, It downloaded the python file instead of opening in browser. This is where i got stuck to go ahead. I googled and tried to fix the solution. After struggling more than one hour, i found that browser is not recognized the the cgi script file.
It means that some configuration is missing for setting up MIME type in apache server. The actual file to be configured is mime.conf in /etc/apache2/mods-enabled/mime.conf. I just uncomment this line
AddHandler cgi-script .cgi
and add .py at the end of this line to look like
AddHandler cgi-script .cgi .py
Now restart your server $ sudo /etc/init.d/apache2 restart and run the index.py file in browser.
Cheers,