CGI Using Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

CGI using Python

Common Gateway Interface


What is CGI?

•The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers
such as HTTP servers.
•The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing

•Your browser contacts the HTTP web server and demands for the URL,
i.e., filename.
•Web Server parses the URL and looks for the filename. If it finds that file
then sends it back to the browser, otherwise sends an error message
indicating that you requested a wrong file.
•Web browser takes response from web server and displays either the
received file or error message.
CGI Architecture Diagram
Web Server Support and Configuration
• <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
• #!/usr/bin/python

• print ("Content-type:text/html\r\n\r\n“)
• print ('<html>’)
• print ('<head>’)
• print ('<title>Hello World - First CGI Program</title>’)
• print ('</head>’)
• print ('<body>’)
• print ('<h2>Hello World! This is my first CGI program</h2>’)
• print ('</body>’)
• print ('</html>’)
HTTP Header
1 Content-type:
A MIME string defining the format of the file being returned. Example is Content-type:text/html
2 Expires: 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.
3 Location: URL
The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.
4 Last-modified: Date
The date of last modification of the resource.
5 Content-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.
6 Set-Cookie: String
Set the cookie passed through the string
Passing Information using GET method
The GET method sends the encoded user information appended to the
page request. The page and the encoded information are separated by
the ? character as follows −

http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2

You can pass information by simply concatenating key and value pairs
along with any URL or you can use HTML <FORM> tags to pass
information using GET method.
FORM Example:GET Method
<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>
URL Example:Get Method
#!/usr/bin/python
import cgi, cgitb
form = cgi.FieldStorage()
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><title>Hello - Second CGI Program</title> </head>“)
print ("<body>“)
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>“)
print ("</html>“)
FORM Example: POST Method
<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>
POST Method
#!/usr/bin/python
import cgi, cgitb
form = cgi.FieldStorage()
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><title>Hello - Second CGI Program</title> </head>“)
print ("<body>“)
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>“)
print ("</html>“)
Passing Checkbox Data
<form action = "/cgi-bin/checkbox.cgi" method = "POST">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
Check box input
if form.getvalue('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF“
print ("<h2> CheckBox Maths is : %s</h2>" % math_flag)
print ("<h2> CheckBox Physics is : %s</h2>" % physics_flag)
Radio Button Data
<form action = "/cgi-bin/radiobutton.py" method = "post" target =
"_blank">
<input type = "radio" name = "subject" value = "maths" /> Maths
<input type = "radio" name = "subject" value = "physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
Radio button data fetch
if form.getvalue('subject'):
subject = form.getvalue('subject')
else:
subject = "Not set“
print ("<h2> Selected Subject is %s</h2>" % subject)
Text Area Data
<form action = "/cgi-bin/textarea.py" method = "post" target =
"_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
Text area CGI fetch
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
text_content = "Not entered“
print ("<h2> Entered Text Content is %s</h2>" % text_content)
Drop Down Box
<form action = "/cgi-bin/dropdown.py" method = "post" >
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
Drop Down CGI data
if form.getvalue('dropdown'):
subject = form.getvalue('dropdown')
else:
subject = "Not entered"
print ("<h2> Selected Subject is %s</h2>" % subject)
File Upload
<html>
<body>
<form enctype = "multipart/form-data"
action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
File upload catch
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
fileitem = form['filename']
if (fileitem.filename):
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
File Download
#!/usr/bin/python
print ("Content-Type:application/octet-stream; name = \"FileName\"\r\
n“);
print ("Content-Disposition: attachment; filename = \"FileName\"\r\n\
n“);
f= open(“test.txt", "rb")
str = f.read();
print (str)
f.close()
Using Cookies in CGI
• maintain session information among different pages in a stateless protocol
(http)
• Cookie are plain text record on the visitor’s hard drive
Expires − The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value
pairs.
Setting up Cookies
#!/usr/bin/python
print ("Set-Cookie:UserID = XYZ;\r\n“)
print ("Set-Cookie:Password = XYZ123;\r\n“)
print ("Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n“)
print ("Set-Cookie:Domain = www.abc.com;\r\n“)
print ("Set-Cookie:Path = /perl;\n“)
print ("Content-type:text/html\r\n\r\n“)
...........Rest of the HTML Content....
Retrieving Cookies
#!/usr/bin/python
from os import environ
import cgi, cgitb
if environ.has_key('HTTP_COOKIE'):
for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
(key, value ) = split(cookie, '=');
if key == "UserID":
user_id = value
if key == "Password":
password = value
print "User ID = %s" % user_id
print "Password = %s" % password

You might also like