Cookies and Python

Newhard, Nick nnewhard at origin.ea.com
Tue Mar 7 01:27:23 CET 2000


This is my first post to the Python List.  Be gentle.

I am relatively new to Python, but even more green when it comes to HTML and
CGI.  In the code snippet below, I am trying to create an index.cgi file
that looks for a username cookie and if it doesn't find one, provides and
processes a form for the username and then saves a cookie.  (Yes, I realize
there is some redundant cookie setting code in there.)  

The problem is, the cookie never seems to get saved between browser sessions
.  The odd thing is, an earlier version worked, placing the cookie in a file
(roughly) called nnewhard at myservername[1].txt   I've since tried to
duplicate the smaller, working version to no avail.

The IE 5.x browser is running under Windows 98 and I check the
\Windows\Cookies subdirectory for a cookie.  The server is the latest Apache
under RedHat Linux.

#!/usr/bin/python

import os, cgi, Cookie, time

# Setup the HTML page
print "Content-type: text/html"
print
print "<HTML><HEAD><TITLE>None</TITLE></HEAD><BODY>"

# create a CGI form
form = cgi.FieldStorage()

# Create a cookie expiration date 10 years from now
ckExpires = time.gmtime(time.time())
ckExpires = (ckExpires[0] + 10,) + ckExpires[1:]

# Create a cookie
#    If the env. var. HTTP_COOKIE does not exist, then
#    we create an empty cookie.
ck = Cookie.Cookie( os.environ.get("HTTP_COOKIE", "") )

# Check for a saved cookie entry
try:
    ckUserName = ck["username"].value
except:
    print "Cookie has no username<BR>"
    # Check CGI form for a corresponding post parameter
    try:
        ckUserName = form["username"].value
    except:
        # Send a form request to the client for a username
        print """
        <pre>Enter your desired username:</pre>
        <form action="index.cgi" method="POST">
        <input type="text" name="username">
        </form>
        """
    else:
        print "Incoming form post has username: %s<BR>" % ckUserName
        ck["username"] = ckUserName
        ck["username"]["expires"] = time.strftime("%a, %d-%b-%Y %T GMT",
ckExpires)
        ck["username"]["path"] = "/"
else:
    print "Cookie has username: %s<BR>" % ckUserName
    ck["username"] = ckUserName
    ck["username"]["expires"] = time.strftime("%a, %d-%b-%Y %T GMT",
ckExpires)
    ck["username"]["path"] = "/"

# End the HTML page
print "</BODY></HTML>"




More information about the Python-list mailing list