WEB DEVELOPER SITE
PHP7
 

Python - CGI Programming


Common Gateway Interface, or CGI, is a lot of models that characterize how data is traded between the web server and a custom content.

What is CGI?

  • The Common Gateway Interface, or CGI, is a standard for outer portal projects to interface with data servers, for example, HTTP servers.

  • The current variant is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

In this section idea of CGI when you click a hyper connection to peruse a specific site page or URL.
  • Your program contacts the HTTP web server and requests for the URL, i.e., filename.

  • Web Server parses the URL and searches for the filename. On the off chance that it finds that record, at that point sends it back to the program, generally sends a mistake message showing that you mentioned a wrong file.

  • Web program takes reaction from web server and shows either the got record or mistake message.

HTTP server so that at whatever point a document in a specific catalog is mentioned that record isn't sent back; rather it is executed as a program, and whatever that program yields is sent back for your program to show. These CGI projects can be a Python Script, PERL Script, Shell Script, C or C++ program, and so forth.

Web Server Support and Configuration

All the CGI Programs to be executed by the HTTP server are kept in a pre-designed index. This index is called CGI Directory and by tradition it is named as/var/www/cgi-container.

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options ExecCGI
    Order allow,deny
    Allow from all
</Directory>

<Directory "/var/www/cgi-bin">
Options All
</Directory>

First CGI Program

running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.
#!/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>'
If you click hello.py, then this produces the following output

Hello Word! This is my first CGI program


There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n.

HTTP Header

The line Content-type:text/html\r\n\r\n is a piece of HTTP header which is sent to the program to comprehend the substance. All the HTTP header will be in the accompanying structure

HTTP Field Name: Field Content 

For Example 

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

Sr.No. Header & Description
1

Content-type:

A MIME string characterizing the arrangement of the document being returned. Model is Content-type:text/html

2

Expires: Date

The date the data ends up invalid. It is utilized by the program to choose when a page should be revived. A substantial date string is in the organization 01 Jan 1998 12:00:00 GMT.

3

Location: URL

The URL that is returned rather than the URL mentioned. You can utilize this field to divert a solicitation to any file.

4

Last-changed: Date

The date of last change of the resource.

5

Content-length: N

The length, in bytes, of the information being returned. The program utilizes this incentive to report the evaluated download time for a file.

6

Set-Cookie: String

Set the treat went through the string

CGI Environment Variables

All the CGI programs approach the accompanying condition factors. These factors assume a vital job while composing any CGI program.

Sr.No. Variable Name & Description
1

CONTENT_TYPE

The information kind of the substance. Utilized when the customer is sending connected substance to the server. For instance, document upload.

2

CONTENT_LENGTH

The length of the question data. It is accessible just for POST requests.

3

HTTP_COOKIE

Returns the set treats as key & esteem pair.

4

HTTP_USER_AGENT

The User-Agent demand header field contains data about the client operator beginning the solicitation. It is name of the web browser.

5

PATH_INFO

The way for the CGI script.

6

QUERY_STRING

The URL-encoded data that is sent with GET strategy request.

7

REMOTE_ADDR

The IP address of the remote host making the solicitation. This is helpful logging or for authentication.

8

REMOTE_HOST

The completely qualified name of the host making the solicitation. On the off chance that this data isn't accessible, at that point REMOTE_ADDR can be utilized to get IR address.

9

REQUEST_METHOD

The technique used to make the solicitation. The most well-known strategies are GET and POST.

10

SCRIPT_FILENAME

The full way to the CGI script.

11

SCRIPT_NAME

The name of the CGI script.

12

SERVER_NAME

The server's hostname or IP Address

13

SERVER_SOFTWARE

The name and form of the product the server is running.

here small CGI program to list out all the CGI variables
#!/usr/bin/python

import os
print "Content-type: content/html\r\n\r\n"; 

print "Environment<\br>"; 

for param in os.environ.keys(): 

print "%20s: %s<\br>" % (param, os.environ[param]) 

GET and POST Methods

Most of program utilizes two techniques two pass this data to web server. These strategies are GET Method and POST Method.

Passing Information utilizing GET method

The GET technique sends the encoded client data added to the page demand. The page and the encoded data are isolated by the ? character as followsc

 

http://www.test.com/cgi-receptacle/hello.py?key1=option1&key2=option2 

The GET technique has estimate restriction: just 1024 characters can be sent in a solicitation string. The GET technique sends data utilizing QUERY_STRING header and will be available in your CGI Program through QUERY_STRING condition variable.

Simple URL Example:Get Method

Here is a straightforward URL, which passes two qualities to hello_get.py program utilizing GET strategy.

/cgi-canister/hello_get.py?first_name=Hello&last_name=Welookups

hello_get.py content to deal with information given by internet browser. We are going to utilize cgi module

#!/usr/canister/python 

# Import modules for CGI taking care of 

import cgi, cgitb 

# Create occurrence of FieldStorage 

structure = cgi.FieldStorage() 

# Get information from fields 

first_name = form.getvalue('first_name') 

last_name = form.getvalue('last_name')


print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
This would generate the following result

Hello Welookups

Simple FORM Example:GET Method

This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.

<form action = "/cgi-bin/hello_get.py" method = "get">
First Name: <input type = "text" name = "first_name">  <br />

Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result.

First Name:
Last Name:

Passing Information Using POST Method

This message comes into the CGI script in the form of the standard input. Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />
</form>

Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.

First Name:
Last Name:

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes −

<form action = "#" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Home
<input type = "checkbox" name = "physics" value = "on" /> Schools
<input type = "submit" value = "Select Place" />
</form>

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
if form.getvalue('Home'):
   home_flag = "ON"
else:
   home_flag = "OFF"

if form.getvalue('Schools'):
   schools_flag = "ON"
else:
   schools_flag = "OFF"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % home_flag
print "<h2> CheckBox Physics is : %s</h2>" % schools_flag
print "</body>"
print "</html>"

Passing Radio Button Data to CGI Program

Radio Buttons are utilized when just a single alternative is required to be selected.

Here is precedent HTML code for a structure with two radio catches −

<form activity = "/cgi-canister/radiobutton.py" strategy = "post" target = "_blank"> 

<input type = "radio" name = "place" esteem = "home"/> Home 

<input type = "radio" name = "place" esteem = "schools"/> Schools 

<input type = "submit" esteem = "Select Place"/>

</form>

The result of this code is the following form −

Home Schools

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

# Import modules for CGI handling
import cgi, cgitb

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
if form.getvalue('homes'):
    home_flag = "ON"
else:
    home_flag = "OFF"

if form.getvalue('physics'):
    schools_flag = "ON"
else:
    schools_flag = "OFF"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Home is : %s</h2>" % home_flag
print "<h2> CheckBox Schools is : %s</h2>" % schools_flag
print "</body>"
print "</html>"

Passing Text Area Data to CGI Program

TEXTAREA component is utilized when multiline content must be passed to the CGI Program.

Here is precedent HTML code for a structure with a TEXTAREA box

<form activity = "/cgi-container/textarea.py" strategy = "post" target = "_blank"> 

<textarea name = "textcontent" cols = "40" lines = "4"> 

Type your content here... 

</textarea> 

<input type = "submit" esteem = "Submit"/> 

</form> 

The aftereffect of this code is the accompanying structure −

Below is textarea.cgi content to deal with information given by internet browser −

#!/usr/canister/python 

# Import modules for CGI taking care of 

import cgi, cgitb 

# Create occasion of FieldStorage 

structure = cgi.FieldStorage() 

# Get information from fields 

in the event that form.getvalue('textcontent'): 

text_content = form.getvalue('textcontent') 

else: 

text_content = "Not entered"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"