How to send cookies

Alex Martelli aleaxit at yahoo.com
Thu Jan 4 12:01:29 EST 2001


"David López" <dlopezp at norsistemas.es> wrote in message
news:newscache$ylbn6g$ss1$1 at news.cesatel.es...
> Hello.
>
> My question is about cookies. I don´t know how to send or receive cookies
in
> Python. Could someone give me a explained example?

The Cookie standard module of the Python libraries, documented at
11.17.3 in the Python Library Reference, has a long example without
all that much explanation -- just an interactive session showing
what 'Set-Cookie:' headers you can expect from a 'smart cookie',
and how you use the .load method of a smart cookie object to get
it (usable as a Python dictionary) back from the HTTP header
strings.  Smart-Cookies are a security exposure, as the docs
tell you right at 11.17.2, so sticking with SimpleCookie's may
be best anyway, even though they limit you to string keys/values.

It's a bit hard to know where to start explaining from, not being
familiar with what you know about cookies, and HTTP, in general -- do
you know RFC 2109 by heart, and just need help seeing how cookies
are set and retrieved _in Python_ specifically; or, at the other
extreme, are you totally unfamiliar with these issues, and need
a very basic tutorial...?

Assuming the latter... your interest in cookies will typically
be in a CGI script.  If a cookie for you was set, you will find
its string in the HTTP_COOKIE environment variable, which you
can access (after an 'import os' statement in your script, of
course) as os.environ['HTTP_COOKIE'] if it's set.

So, early in your script, you will typically have:

import cgi
import os
import Cookie

cookie = Cookie.SimpleCookie()
if os.environ.has_key('HTTP_COOKIE'):
    # some cookie for us, let's read it
    cookie.load(os.environ['HTTP_COOKIE'])
else:
    # no cookie for us, let's fake it
    # possibly setting default-values
    cookie['color']='red'

Now, you proceed with the rest of your CGI processing -- just
*don't* terminate the headers (to start doing other output)
before you determine if you need to send back a set-cookie,
since THAT one goes in the headers too!  If you have suitably
modified the above-created cookie, and want to send it back,
then your script's header-output portion may be, e.g.:

    print "Content-type: text/html"
    print cookie
    print

then, the rest of your output.  Next time this client visits
you (if it has cookies enabled, only), your cookie will get
restored to what you're now setting (strings only, being a
SimpleCookie; but that IS normally what you want).

Is that what you needed to know...?


Alex






More information about the Python-list mailing list