First CGI Program in Python

PythonServer Side ProgrammingProgramming

Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.

Example

#!/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>'

Output

If you click hello.py, then this produces the following output −

Hello Word! This is my first CGI program

This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen.

By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form −

HTTP Field Name: Field Content

Example

Content-type: text/html\r\n\r\n

There are few other important HTTP headers, which you will use frequently in your CGI Programming.

Sr.No.Header & Description
1Content-type:
A MIME string defining the format of the file being returned. Example is Content-type:text/html
2Expires: Date
The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.
3Location: URL
The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.
4Last-modified: Date
The date of last modification of the resource.
5Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
6Set-Cookie: String
Set the cookie passed through the string
raja
Published on 31-Jan-2020 07:47:12
Advertisements