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

CGI

CGI: Helping Web Servers Process


Client Data
• Introduction to CGI:
• The Web was initially developed to be a global online repository or archive of
(mostly educational and research-oriented) documents. Such pieces of information
generally come in the form of static text and usually in HTML.
• These (static) HTML documents live on the Web server and are sent to clients
when and if requested.
• As the Internet and Web services evolved, there grew a need to process user
input. Online retailers needed to be able to take individual orders, and online
banks and search engine portals needed to create accounts for individual users.
• Thus fill-out forms were invented, and became the only way a Web site can get
specific information from users .
• This, in turn, required the HTML now be generated on the fly, for each client
submitting user-specific data. i.e. when client requests for a file, that file is not
sent back but it is executes as a program and o/p of the program is sent back to
browser.
CGI
• Now, Web servers are only really good at one thing, getting a user request for a file
and returning that file (i.e., an HTML file) to the client. They do not have the
“brains” to be able to deal with user-specific data such as those which come from
fields.
• Not being their responsibility, Web servers farm out such requests to external
applications which create the dynamically generated HTML that is returned to the
client.
• The entire process begins when the Web server receives a client request (i.e., GET
or POST) and calls the appropriate application. It then waits for the resulting HTML
—meanwhile, the client also waits.
• Once the application has completed, it passes the dynamically generated HTML
back to the server, who then (finally) forwards it back to the user. This process of
the server receiving a form, contacting an external application, and receiving and
returning the newly-generated HTML takes place through what is called the Web
server’s CGI (Common Gateway Interface)
CGI
CGI
• CGI applications that create the HTML are usually
written in one of many higher-level programming
languages that have the ability to accept user data,
process it, and return HTML back to the server
• Currently used programming languages include Perl,
PHP, C/C++, or Python
CGI
• Common Gateway Interface (also known as CGI) is not a kind of language
but just a specification(set of rules) that helps to establish a dynamic
interaction between a web application and the browser (or the client
application). The CGI programs make possible communication between
client and web servers.
• Whenever the client browser sends a request to the webserver the CGI
programs send the output back to the web server based on the input
provided by the client-server.
• The Common Gateway Interface is a standard for external gateway
programs to interface with the server, such as HTTP Servers.
• it is the collection of methods used to set up a dynamic interaction
between the server, and the client application. When a client sends a
request to the webserver, the CGI programs execute that particular
request and send back the result to the webserver.
Running First Python File as CGI
• Before running CGI programs, we must ensure
that our system has the following configuration-
• Apache Server
• Python

• Install the XAMPP(cross-platform,


Apache, MySQL, PHP, and Perl) server
• Configure XAMPP (Start Apache)
First Program
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• print("Content-type:text/html\r\n\r\n")
• print('<html>')
• print('<head>')
• print("First Page")
• print('</head>')
• print('<body>')
• print("Welcome")
• print('</body>')
• print('</html>')

• Strore above program (test.py) in c:\xampp\cgi-bin


• Type the localhost/cgi-bin/test.py into the web browser. It will display the following output.
First Program
Structure of a Python CGI Program

• First line in the script must be path to python executable otherwise we


may get errors. OS must know what is the name of executable which is
going to run cgi script.
• The CGI script must contain two sections which separated by a blank line.
• The header must be in the first section and the second section will contain
the kind of data that will be used during the execution of the script.
• Content type in first section is HTTP header that let the client and server
pass additional information with HTTP request and response. If the output
of the script is to be interpreted as HTML then the content type will be
text/html. This line is sent back to the browser and it specifies the content
type to be displayed on the browser screen is HTML.
• The blank line signals the end of the header and is required.
Example(Passing form data to CGI program)
• Write the following html program in notepad and save as
formtest.html on c:\xampp\htdocs directory

• <html>
• <body>
• <form method = 'post' action = '/cgi-bin/formtest.py' target = _blank>
• First Name: <input type = 'text' name = 'first_name'> <br />

• Last Name: <input type = 'text' name = 'last_name' />


• <input type = 'submit' value = 'Submit' />
• </html>
• </body>
• action=" URL “ ---the form data is sent to this URL
• method (Specifies the HTTP method to use when sending form-data)
• POST: The POST method sends the form data in the body of the HTTP
request.
(A large amount of data can be sent.)
• GET: The GET method sends the form data within the URL.
http://www.example.com/example.cgi?name1=value1&name2=value2
(There are limits to the number of characters that can be sent.)
• Target: The target attribute specifies a name or a keyword that indicates
where to display the response that is received after submitting the form.
• Target = _blank:The response is displayed in a new window or tab
• Target = _self:
The response is displayed in the same frame (this is default)
Example
• Write the following CGI script(formtest.py) and save in c:\xampp\cgi-bin directory
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe

• # Import modules for CGI handling


• import cgi
• print("Content-type: text/html\r\n\r\n")
• print("<html><body>")
• print("<h1> Hello Program! </h1>")
• # Using the inbuilt methods
• # Create instance of FieldStorage
• form = cgi.FieldStorage()
• # Get data from fields
• if form.getvalue("first_name"):
• first_name = form.getvalue('first_name')
• last_name = form.getvalue('last_name')
• print("<h2>Hello %s %s</h2>" % (first_name, last_name))
• print("</body></html>")

• The FieldStorage class is used to read the form contents.


• The FieldStorage instance can be indexed like a Python dictionary
• Here the fields, accessed through "form[key]", are themselves instances of FieldStorage , depending on the form encoding).
The value attribute of the instance yields the string value of the field. The getvalue() method returns this string values of the
fields.
RUNNING CGI SCRIPT
• Type the localhost/formtest.html into the web
browser. It will display the following output.
RUNNING CGI SCRIPT
• On clicking the submit button, server will run formtest.py CGI
script and return back the html output to client which will
display following output:
Example
• Write the following html program in notepad and save as hello.html on
c:\xampp\htdocs directory
• <html>
• <body>
• # Using HTML input and forms method
• <form method='post' action='\cgi-bin\hello.py'>
• <p>Name: <input type='text' name='name' /></p>
• <input type='checkbox' name='happy' /> Happy
• <input type='checkbox' name='sad' /> Sad
• <input type='submit' value='Submit' />
• </form>
• </html>
• </body>
Running CGI Script
• Write the following CGI script(hello.py) and save in c:\xampp\cgi-bin directory
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• # Importing the 'cgi' module
• import cgi
• print("Content-type: text/html\r\n\r\n")
• print("<html><body>")
• print("<h1> Hello Program! </h1>")
• # Using the inbuilt methods

• form = cgi.FieldStorage()
• if form.getvalue("name"):
• name = form.getvalue("name")
• print("<h1>Hello" +name+"! Thanks for using my script!</h1><br />")
• if form.getvalue("happy"):
• print("<p> Yayy! I'm happy too! </p>")
• if form.getvalue("sad"):
• print("<p> Oh no! Why are you sad? </p>")
• print("</body></html>")
Running CGI Script
• Type the localhost/hello.html into the web
browser. It will display the following output.
Running CGI Script
• On clicking submit button, it will display:
Advanced CGI
• Cookies
• HTTP is said to be a stateless protocol. What this means for web
programmers is that every time a user loads a page it is the first time for
the server. The server can’t say whether this user has ever visited that
site, if the user was in the middle of a buying transaction, if he has
already authenticated, etc.
• A cookie is a tag that can be placed on the user’s computer. Whenever
the user loads a page from a site the site’s script can send him a cookie.
The cookie can contain anything the site needs to keep the state of
including the identity of the user. Then within the next request the client
does for a new page there goes back the cookie with all the pertinent
information to be read by the server script.
• Cookies are data stored by web server on client computer, managed by
the browser.
COOKIE
• The environment variable HTTP_COOKIE is set by the web
server. When we rerun a web page the cookies are retrieved
as follows:
• >>> from os import environ
• >>> environ['HTTP_COOKIE'] = 'z = 3'
• >>> d=SimpleCookie(environ['HTTP_COOKIE'])
• >>> d['z'].value
• '3'
Set the Cookie

• There are two basic cookie operations. The


first is to set the cookie as an HTTP header to
be sent to the client. The second is to read the
cookie returned from the client also as an
HTTP header.
• This script will do the first one placing a cookie
on the client’s browser:
COOKIE
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• import time

• # This is the message that contains the cookie


• # and will be sent in the HTTP header to the client
• print('Set-Cookie: lastvisit=' + str(time.time()));

• Key Value
• # To save one line of code
• # we replaced the print command with a '\n'
• print ('Content-Type: text/html\n')
• # End of HTTP header

• print ('<html><body>')
• print ('Server time is', time.asctime(time.localtime()))
• print ('</body></html>')
Set Cookie using http.cookies Module
• from http.cookies import SimpleCookie
• >>> c= SimpleCookie()
• >>> c["a"]= 1
• >>> c["b"]=2
• >>> print(c) // Generate HTTP Headers
• Set-Cookie: a=1

• Set-Cookie: b=2
The Cookie Object

• The Cookie module can save us a lot of coding and errors . A cookie can be set using following script:
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• import time
• from http.cookies import SimpleCookie

• # Instantiate a SimpleCookie object


• cookie = SimpleCookie()

• # The SimpleCookie instance is a mapping


• cookie['lastvisit'] = str(time.time()) // The output is a valid Set-Cookie header ready to be passed to the client as part of the HTTP
response

• # Output the HTTP message containing the cookie


• print (cookie)
• print('Content-Type: text/html\n')

• print('<html><body>')
• print('Server time is', time.asctime(time.localtime()))
• print('</body></html>')

• Save and run this code from your browser and take a look at the cookie saved there. Search for the
cookie name,’lastvisit’.
Reading Cookie Value by server
• The returned cookie will be available as a string in the
os.environ dictionary with the HTTP_COOKIE key. The
environment variable HTTP_COOKIE is set by the web server.
When we rerun a web page the cookies are retrieved as
follows:

cookie_string = os.environ.get('HTTP_COOKIE')
• Cookie_string will contain all cookies set by server. This
environment variables is formatted as a series
of key=value pairs delimited by semicolons.
Gettingcookievalue.py
• #! C:\Users\840 G2\AppData\Local\Programs\Python\Python38-32\python.exe
• import time, os
• from http.cookies import SimpleCookie

• cookie = SimpleCookie()
• cookie['lastvisit'] = str(time.time())

• print(cookie)
• print('Content-Type: text/html\n')

• print('<html><body>')
• print('<p>Server time is', time.asctime(time.localtime()), '</p>')

• # The returned cookie is available in the os.environ dictionary


• cookie_string = os.environ.get('HTTP_COOKIE')

• # The first time the page is run there will be no cookies


• if not cookie_string:
• print('<p>First visit or cookies disabled</p>')

• else: # Run the page twice to retrieve the cookie


• print('<p>The returned cookie string was "' + cookie_string + '"</p>')

• # load() parses the cookie string


• cookie.load(cookie_string)
• # Use the value attribute of the cookie to get it
• lastvisit = float(cookie['lastvisit'].value)

• print('<p>Your last visit was at',)


• print(time.asctime(time.localtime(lastvisit)), '</p>')

• print('</body></html>')
Cookie
• We will write a script to
• retrieve cookie, initialize counter to zero, or
• increment the value of counter by one, and then
• display the counter value on the page.
Countercookies.py
• import os
• from http.cookies import SimpleCookie

• def increment():
• """
• Retrieves cookie, either initializes counter,
• or increments the counter by one.
• """
• if 'HTTP_COOKIE' in os.environ:
• cnt = SimpleCookie(os.environ['HTTP_COOKIE'])
• else:
• cnt = SimpleCookie()
• if 'visits' not in cnt:
• cnt['visits'] = 0
• else:
• cnt['visits'] = str(1 + int(cnt['visits'].value))
• return cnt

• def main():
• """
• Retrieves a cookie and writes
• the value of counter to the page,
• after incrementing the counter.
• """
• counter = increment()
• print(counter)
• print("Content-Type: text/plain\n")
• print("counter: %s" % counter['visits'].value)

You might also like