The standard Python Cookie module has the
operations you will need to handle cookies. Import it
like this:
import Cookie
To create a new cookie from a string c:
s
c= Cookie.SimpleCookie (s)
Internally, a cookie is a set of key-value pairs. Most
applications use only one name and one value, but it is
possible to have several. Each key-value pair is kept
in an instance of class Morsel.
Here are the operations on an instance of class CSimpleCookie.
C.has_key (
key )
Returns True if has a key that matches
Ckey; otherwise, it returns False.
C[key]
Return the Morsel instance for the
given , if there is one, otherwise raise keyKeyError.
C[key] = s
Add a new Morsel to with the
given C and some string value key.
s
print C.output()
Do this to set as the current cookie, before you have
sent any other headers such as the CContent-type header.
Here are the operations on a Morsel
instances .
M
M.key
The key for this morsel.
M.value
The value for this morsel.
Instances of Morsel also act like
dictionaries, except that only certain keys are allowed.
You may read or set entries in this dictionary.
Allowable keys include:
'max-age'
The cookie's maximum age in seconds. If you would like to log the user out of your site after a set period of time, you can use this attribute to determine when their cookie will expire.
You can set this value to a large interval, such as five years, to create what is called a persistent cookie. Such a cookie will live on even when the user kills and restarts their browser.
Setting this value to zero ('0')
causes the cookie to be deleted.
'path'
Use this value to limit this cookie to only a
certain directory on your site. It Specifies the
URL of the top directory of your site, relative to
the server. For example, if your site's pages are
all at or below the URL http://www.nmt.edu/~pat/cgi/, the relative
path would be '/~pat/cgi/'.
If you specify this attribute, users who come to your server but not inside your site will not see your cookies.
'secure'
Set this attribute to any value to request that
cookies be carried only through secure channels
such as the https: protocol.
Disclaimer: This is not a complete security
mechanism. Seek expert help if you are handling
sensitive data.
'comment'
You may set a value for this attribute as a comment to explain what the cookie is for. Users can ask their browser to show them this comment while they are deciding whether or not to accept your cookie.