Setting expirty data on a cookie

David wizzardx at gmail.com
Fri Apr 25 15:31:25 EDT 2008


>  import Cookie
>  import time
>  c = Cookie.SimpleCookie()
>  c['data'] = "unamepwordwhatever"
>  c['data']['expires'] = 30 * 24 * 60 * 60
>  print c
>
>  Gives an output of:
>
>  "Set-Cookie: data=unamepwordwhatever; expires=Sat, 24-May-2008
>  12:11:36 GMT"
>

Hi again. I didn't see your replies until now.

Disclaimer: I've never worked with cookies before, I'm just going by
the rfc, python docs, and wikipedia.

I think the confusion exists because the Cookie module has an unusual
definition of cookies. What we call cookies (key + value +
attributes), the Cookie module calls a Morsel. What the Cookie module
calls a cookie is in fact the collection of Set-Cookie headers that
will be sent by the server.

So for code like this:

c = Cookie.SimpleCookie()
c['data1'] = 123
c['data2'] = 456

the server will output 2 cookies like this:

Set-Cookie: data1=123
Set-Cookie: data2=456

This is why when you want to set the expiry date for one of the
cookies, you need syntax like this:

c['data2']['expires'] = 30 * 24 * 60 * 60

Another note: 'expires' is apprantly a legacy attribute for early
Netscape browsers. The RFC and python source comments suggest that you
use 'Max-Age' instead.

I think that the Cookie module author wanted to represent http state
as a python dictionary, but chose an unfortunate name for the class.
Also, the example page doesn't go into detail about setting
attributes.

David.



More information about the Python-list mailing list