Cookie not reading first time though...

Rene renx99 at
Sat Oct 30 18:04:08 CEST 2004

I'm trying to learn how to use python for cgi scripts...

I created a form that submits some info that I put in a cookie.  Then 
the script calls itself and reads the cookie, and displays a different 
form to get more information.

The problem I'm running into is the script is setting the cookie... but 
it doesn't read it the first time through for some reason, if I 
immediately try it again it works fine.  So for some reason it's not 
picking up the cookie the first time. 

Would it be a better idea to break the script into two different scripts 
to accomplish this?

Any advise would be appreciated, please be gentle, I'm still a newbie 

here is the script:


import cgi,os,Cookie
import cgitb; cgitb.enable()

def name_race():
    print "Content-Type: text/html\n\n"
    print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" 
    print "<html>"
    print "<body>"
    print "<form method = post ACTION =\"\"> "
    print "<table><tr>"
    print "<td><b>Name:</b></td><td><input type=text name=\"name\"></td>
    print "</table>"
    print "<p>"
    print "<table>"
    print "<tr>"
    print "<td><b>Race:</b></td></tr>"
    print "<tr>"
    print "<td>Human</td><td><input type=radio name=\"race\" value=\"1
    print "<tr>"
    print "<td>Elf</td><td><input type=radio name=\"race\" value=\"2\">
    print "</table>"
    print "<p>"
    print "<input type = hidden name=\"action\" value=\"getclass\">"
    print "<input type = submit value =\"Enter\">"

def pick_class():
    mycookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", ""))
    race = mycookie["race"].value
    name = mycookie["name"].value
    print "Content-Type: text/html\n\n"
    print "<html>"
    print "<body>"
    print name
    print race
    print "</body>\n</html>"

def print_sheet():

def main():
    form = cgi.FieldStorage()
    mycookie = Cookie.SmartCookie()	
    if form.has_key("name") and form.has_key("race"):
        if (form["action"].value == "getclass"):
	    mycookie["name"] = form["name"].value
	    mycookie["name"]["max-age"] = 60
	    mycookie["race"] = form["race"].value
	    mycookie["race"]["max-age"] = 60
	    print mycookie
    else: name_race()


More information about the Python-list mailing list