Cookies and Python

Timothy O'Malley timo at alum.mit.edu
Tue Mar 7 04:08:43 CET 2000


hola.

In article 

 Newhard, Nick <nnewhard at origin.ea.com> wrote:
> This is my first post to the Python List.  Be gentle.

Don't worry, you didn't mention anything about whitespace.  You'll be
fine. :)

> The problem is, the cookie never seems to get saved between browser sessions

That's because you never send it back to the client browser.  You need
to send the cookie value in the headers.  This means you should send
the cookie value IMMEDIATELY following the "Content-Type:" header.

Here's an untested skeleton for what you propose (notice that I print
the cookie 'ck' immediately after the content-type):




import os, cgi, Cookie

# First we create the cookie and form
ck   = Cookie.SmartCookie( os.environ.get("HTTP_COOKIE", "") )
form = cgi.FieldStorage()

# Look for the username
if ck.has_key("username") or form.has_key("username"):
    # There is a username present
    username = ck.get("username", form["username"]).value
    ck["username"] = username
    ck["username"]["path"] = "/"
    ck["username"]["expires"] = 10 * 365 * 24 * 3600

    html_text = "<HTML><BODY>User is %s</BODY></HTML>" % username

else:
    # There is no username present
    ck["username"] = "UNKNOWN"
    ck["username"]["path"] = "/"
    ck["username"]["expires"] = -3600
    
    html_text = """
        <pre>Enter your desired username:</pre>
        <form action="index.cgi" method="POST">
        <input type="text" name="username">
        </form>
    """


# Now send the resulting page

print "Content-Type: text/html"
print ck
print
print html_text



More information about the Python-list mailing list