Cookie: Not understanding again

David Wahler dwahler at gmail.com
Sat Jun 2 12:50:05 CEST 2007


On Jun 2, 9:32 am, mosscliffe <mcl.off... at googlemail.com> wrote:
> David,
>
> Thanks for your help.
>
> I spent all last night trying to get it to work, but I can not work
> out how to force my cookie into the response header.  The most
> annoying part is on one occasion it did and the cookie sat there until
> I killed the session.  By the time I discovered 'pageinfo' add-in for
> firefox, the cookie had gone.

Your CGI script needs to produce output of the form:

    Header-1: ...
    Header-2: ...

    response data goes here...

Each line before the blank line is an HTTP header. To send cookies to
the browser, you need to generate a header of the form:

    Set-Cookie: name=value

Printing the SimpleCookie object does this for you.

> I have read a lot about cookies, but the grey matter is very slow at
> absorbing nowadays.  I was wondering if I should add the 'path=/' to
> my cookie, as I am using a host that has numbers for the IP address
> and my domain name when used, is via a frame.  Although the python bit
> to display the contents (when it did work), did not show any value for
> 'path'.

If you specify a path attribute, then the browser will only send the
cookie on requests that begin with that path. If you don't, it
defaults to the URL of the page that generates the cookie. For a
single test script like this, there's no need to bother with it, but
you can set it like this:

>>> cookie["someCookieName"]["path"] = "/path/to/whatever"

> Could I create the response header in python and get it executed as
> part of my form submission ?
>
> Obviously, still struggling.

Here's a simple, complete example to get you started, based loosely on
your original code:

######################################################################

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

def getCookie():
    c = Cookie.SimpleCookie()
    if 'HTTP_COOKIE' in os.environ:
        c.load(os.environ['HTTP_COOKIE'])

    if os.environ['QUERY_STRING'] == 'reset' or 'mysession' not in c:
        c['mysession'] = 0
    else:
        c['mysession'] = int(c['mysession'].value) + 1

    return c

if __name__ == '__main__':

    print "Content-type: text/html"
    myCookie = getCookie()
    print myCookie

    if os.environ['QUERY_STRING'] == 'reset':
        print "Status: 302 Moved"
        print "Location:", os.environ['SCRIPT_NAME']
        print
    else:
        print
        print 'Current Value: ', myCookie['mysession'].value
        print '<br><a href="?reset">Reset Counter</a>'

######################################################################

Hope this helps!

-- David




More information about the Python-list mailing list