Problem dealing with cookies

John J. Lee jjl at
Mon Aug 4 01:39:59 CEST 2003

faizan at (Fazer) writes:

> I have the following code:
> C = Cookie.SimpleCookie()
> C["moo"] = "f"
> C["moo"]["path"] = "/"
> C["moo"]["expires"] = 60*60*60*60
> #Print the headers
> print C

Here (the print statement), you're setting the client's cookie "moo"
to "f", no matter what.  What you wanted was to put the form's data in
the cookie, if the request contains form data.

> print "Content-Type: text/html\n"
> #Print starting html
> print "<html><head><title>Cookie</title></head><body>"
> form = cgi.FieldStorage()
> [...]
> if C['moo'].value != "f":
> 	print "I remember you %s" % (C["moo"].value)

You're expecting C to have magically aquired a new value between the
point where you set it above and this point.  How is that supposed to

> elif form.has_key("name") and C["moo"].value == "f":
> 	print "Thank you %s!" % (form["name"].value)
> 	C["moo"] = form['name'].value

More of the same.  You're setting C["moo"], but how is the client
supposed to find out?  SimpleCookie isn't quite that magical.  :-)

Remember the way all this gets executed: a request comes in, the web
server picks the right CGI script based on the request URL, and your
script sees the HTTP headers (including Cookie) as environment
variables.  You use the headers from the environment (with something
like C.load(os.environ["HTTP_COOKIE"]) and forms = cgi.FieldStorage()
-- both look in os.environ, one explicitly, the other not), then you
output some HTTP headers and then some data (usually HTML).  Request,
response.  You're trying to sneak several request-response cycles into
one CGI execution.

So, you either want a single CGI script and some kind of switch (am I
looking at the first request, before the user has seen the form, or
the second, with the submitted form data?), or two CGI scripts (one
for the first request, one for the second with the form data -- set
the form's action HTML-attribute to point to that second CGI script).

Probably, you'll quickly find that life is simpler (for anything
non-trivial) if you use a web programming framework.  Don't be afraid
of them!  Albatross might be a good choice -- designed to be a small
step up from CGI, and pure Python so easy to install on a server --
but there are plenty of others.

In all cases, remember that you have to assume you're dealing not with
a well-behaved user (no such beast) using a well-behaved browser, but
an evil hacker crafting evil HTTP headers and data exactly how he
wants them.


More information about the Python-list mailing list