How to Delete a Cookie?

tryg.olson at gmail.com tryg.olson at gmail.com
Thu Jan 8 19:33:02 CET 2009


On Jan 8, 1:16 pm, Jose C <houdinihoun... at gmail.com> wrote:
> > c["mycook"]["expires"] = 0
>
> Set ["expires"] using the following format to any time less than
> current (which causes the browser to delete the cookie).
> Here's a function I use to return a cookie expiry timestamp, negative
> values passed in result in cookie being deleted.
>
> def cookie_expiry_date(numdays):
>     """ Returns a cookie expiry date in the required format.  -ve
> value in = kill cookie.
>     `expires` should be a string in the format "Wdy, DD-Mon-YY
> HH:MM:SS GMT"
>     NOTE!  Must use [expires] because earlier IE versions don't
> support [max-age].
>     """
>     from datetime import date, timedelta
>     new = date.today() + timedelta(days = numdays)
>     return new.strftime("%a, %d-%b-%Y 23:59:59 GMT")
>
> Usage:
> c["mycook"]["expires"] = cookie_expiry_date(-10)  # any negative value
> will remove cookie
>
> HTH,
> JC


Jose C's piece of code works to delete the cookie as does setting
["expires"]=0 but ONLY as long as I also set the path.  Why is this?
So what would be the best way to do this.  I tried reading in the
existing cookie (b), creating a new cookie (c) with all the same
values except for the "expires" but this did not get my cookie
deleted.

b = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
c = Cookie.SimpleCookie()
c[cookieName] = b[cookieName].value
c[cookieName]["expires"] = 0
c[cookieName]["path"]    = b[cookieName]["path"]
print c



More information about the Python-list mailing list