Chapter: Internet & World Wide Web HOW TO PROGRAM - Python

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Cookies - Python

When a client visits a Web site, the server for that Web site may write a cookie to the client’s machine.



When a client visits a Web site, the server for that Web site may write a cookie to the client’s machine. This cookie can be accessed by servers within the Web site’s domain at a later time. Cookies are usually small text files used to maintain state information for a par-ticular client. State information may contain a username, password or specific information that might be helpful when a user returns to a Web site. Many Web sites use cookies to store a client’s postal zip code. The zip code is used when the client requests a Web page from the server. The server may send the current weather information or news updates for the client’s region. The scripts in this section write cookie values to the client and retrieve the values for display in the browser.


Figure 28.19 is an XHTML form that asks the user to enter three values. These values are passed to the script, which writes the values in a client-side cookie.


Figure 28.20 is the script that retrieves the form values from fig28_19.html and stores those values in a client-side cookie. Line 6 imports the Cookie module. This module provides capabilities for reading and writing client-side cookies.


Lines 9–15 define function printContent, which prints the content header and XHTML DOCTYPE string to the browser. Line 17 retrieves the form values by using class FieldStorage from module cgi. We handle the form values with a try/except/ else block. The try block (lines 19–22) attempts to retrieve the form values. If the user has not completed one or more of the form fields, the code in this block raises a KeyError exception. The exception is caught in the except block (lines 23–28), and the program calls function printContent, then outputs an appropriate message to the browser.




    "-//W3C//DTD XHTML 1.0 Transitional//EN"


    <!-- Fig. 28.19: fig28_19.html -->

    <html xmlns = "" xml:lang = "en"

    lang = "en">


    <title>Writing a cookie to the client computer</title>


      <body style = "background-image: images/back.gif;

      font-family: Arial,sans-serif; font-size: 11pt" >


      <span style = "font-size: 15pt; font-weight: bold">

      Click Write Cookie to save your cookie data.

      </span><br />

      <form method = "post" action = "/cgi-bin/">

      <span style = "font-weight: bold">Name:</span><br />

      <input type = "text" name = "name" /><br />

      <span style = "font-weight: bold">Height:</span><br />

      <input type = "text" name = "height" /><br />

<span style = "font-weight: bold">Favorite Color</span><br />


      <input type = "text" name = "color" /><br />

      <input type = "submit" value = "Write Cookie" />





Fig. 28.19  XHTML form to get cookie values from user


The code in the else block (lines 29–68) executes after the program successfully retrieves all the form values. Line 32 specifies the format for the expiration value of the cookie. The format characters in this string are defined by the time module. For a com-plete list of time tokens and their meanings, visit



    # Fig. 28.20:

    # Writing a cookie to a client's machine


    import cgi

    import Cookie

    import time

    def printContent():

      print "Content-type: text/html"


      print """

      <html xmlns = "" xml:lang="en"



          <head><title>Cookie values</title></head>"""


      form = cgi.FieldStorage() # get form information


      try:  # extract form values

      name = form[ "name" ].value

      height = form[ "height" ].value

      color = form[ "color" ].value

      except KeyError:


      print """<body><h3>You have not filled in all fields.

      <span style = "color: blue"> Click the Back button,

      fill out the form and resubmit.<br /><br />

      Thank You. </span></h3>"""


      # construct cookie expiration date and path

      expirationFormat = "%A, %d-%b-%y %X %Z"

      expirationTime = time.localtime( time.time() + 300 )

      expirationDate = time.strftime( expirationFormat,

      expirationTime )

      path = "/"

      # construct cookie contents

       cookie = Cookie.Cookie()

       cookie[ "Name" ] = name

      cookie [ "Name" ][ "expires" ] = expirationDate

      cookie[ "Name" ][ "path" ] = path

      cookie[ "Height" ] = height

      cookie[ "Height" ][ "expires" ] = expirationDate

      cookie[ "Height" ][ "path" ] = path

      cookie[ "Color" ] = color

      cookie[ "Color" ][ "expires" ] = expirationDate

      cookie[ "Color" ][ "path" ] = path

      # print cookie to user and page to browser

      print cookie


      print """<body style = "background-image: /images/back.gif;

      font-family: Arial,sans-serif; font-size: 11pt">

      The cookie has been set with the following data: <br /><br />


      <span style = "color: blue">Name:</span> %s<br />

      <span style = "color: blue">Height:</span> %s<br />

      <span style = "color: blue">Favorite Color:</span>

      <span style = "color: %s"> %s</span><br />""" \

      % ( name, height, color, color )


      print """<br /><a href= "">

      Read cookie values</a>"""


      print """</body></html>"""


Fig. 28.20  Writing a cookie to a client’s machine



The time function (line 33) of module time returns a floating-point value that is the number of seconds since the epoch (i.e., January 1, 1970). We add 300 seconds to this value to set the expirationTime for the cookie. We then format the time using the local-time function. This function converts the time in seconds to a nine-element tuple that rep-resents the time in local terms (i.e., according to the time zone of the machine on which the script is running). Lines 34–35 call the strftime function to format a time tuple into a string. This line effectively formats tuple expirationTime as a string that follows the format specified in expirationFormat.


Line 39 creates an instance of class Cookie. An object of class Cookie acts like a dictionary, so values can be set and retrieved using familiar dictionary syntax. Lines 41–51 set the values for the cookie, based on the user-entered values retrieved from the XHMTL form.


Line 54 writes the cookie to the browser (assuming the user’s browser has enabled cookies) by using the print statement. The cookie must be written before we write the content type (line 56) to the browser. Lines 57–65 display the cookie’s values in the browser. We then conclude the else block by creating a link to a Python script that retrieves the stored cookie values (lines 67–68).

Figure 28.21 is the CGI script that retrieves cookie values from the client and displays the values in the browser. Line 18 creates an instance of class Cookie. Line 19 retrieves the cookie values from the client. Cookies are stored as a string in the environment variable HTTP_COOKIE. The load method of class Cookie extracts cookie values from a string. If no cookie value exists, then the program raises a KeyError exception. We catch the exception in lines 20–22 and print an appropriate message in the browser.


If the program successfully retrieves the cookie values, the code in lines 23–37 dis-plays the values in the browser. Because cookies act like dictionaries, we can use the keys method (line 31) to retrieve the names of all the values in the cookie. Lines 32–35 print these names and their corresponding values in a table.



    # Fig. 28.21:

    # Program that retrieves and displays client-side cookie values


    import Cookie

    import os

    print "Content-type: text/html"


      print """

      <html xmlns = "" xml:lang="en"


      <head><title>Cookie values</title></head>

      <body style =

      font-family: Arial, sans-serif; font-size: 11pt">"""


      cookie = Cookie.Cookie()

      cookie.load( os.environ[ "HTTP_COOKIE" ] )

      except KeyError:

      print """<span style = "font-weight: bold">Error reading cookies



      print """<span style = "font-weight: bold">

      The following data is saved in a cookie on your computer.

      </span><br /><br />"""

      print """<table style = "border-width: 5; border-spacing: 0;

      padding: 10">"""

      for item in cookie.keys():

      print """<tr>

      <td style = "background-color: white">%s</td>

      </tr>""" % ( item, cookie[ item ].value )


          print """</table>"""



        print """</body></html>"""


Fig. 28.21  CGI script that retrieves and displays client-side cookie values.

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.