Showing posts with label python 2.7 tutorial. Show all posts
Showing posts with label python 2.7 tutorial. Show all posts

Tuesday, August 11, 2015

A Touch of Python CGI Programming

Python CGI( Common Gateway Interface) is a server side script which help us to write server side auto generated html page. The utility is that with CGI programming you can generate page depending upon the input to the webpage. Before I dig into Python CGI, I need to introduce you to a little bit of html -

<html>
<title>Intro to HTML</title>
<body>This is the body of your webpage</body>
</html>

Write the above line in a text editor, name it something.html and double click it. It will open in your favorite browser and show the lines in between the body and title tag. This is called a html page, please visit some online tutorial for more details.

Now lets write a python cgi file. To run cgi script you have to configure or download servers which supports python cgi scripting. I recommend you to use xampp as it  is easy to use and not so complicated to configure. Download xampp and install it.

The next thing is to open the cgi-bin folder in the c:\xampp folder. You will be writing all your cgi scripts in the folder. So lets create a file and name it 'firstcgi.py'. Write the following in the file and save it -

#!/usr/bin/python """(In case of windows #!/Python27/python probably, you need to check your python installation path to be sure)"""
import cgi
import cgitb
print "content-tpe:text/html\r\n\r\n"
print ""
print """
<html>
<title>Intro to HTML</title>
<body>This is the body of your webpage</body>
</html>
 """
 To run the cgi file you either need to go to the directory of the cgi file and run python CGIHTTPServer or simply run the webserver and type the path http://localhost/cgi-bin/firstcgi.py, see if it runs or not. You will probably find some errors or some 500 error. Why?
A few thing to remember before writing CGI Script  -
  •  Always make the cgi script file executable by going to the properties of the file in case of windows and for linux change it by chmod a+x filename command.
  • You need to change the ownership to  the current user of the file. chmod 775 is a better option for python cgi file, for windows user make it read and writable.
  • Always store the file in cgi-bin folder, it is an obligation of writing cgi script.
  • Make sure you run the CGIHTTPServer command from the same directory where cgi-bin folder is located.     
  • The path to the python executable file is not optional, always start cgi program with the #! followed by python path
 Now check your program in your browser , you will see the same output as the previous html file but only it is generated by python cgi script. What is the use? We will see in next entry .

 

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...