Setting Permanent Cookies

After some trial and error, I came up with this which seems to work:

from WebKit.Cookie import Cookie

class SitePage:
    # ...

    def setPermanentCookie(self, key, value):
        cookie = Cookie(key, value)
        t = time.gmtime(time.time())
        t = (t[0] + 10,) + t[1:]
        t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
        cookie.setExpires(t)
        self.response().addCookie(cookie)

    def deletePermanentCookie(self, key):
        cookie = Cookie(key, '')
        t = time.gmtime(time.time())
        t = (t[0] - 10,) + t[1:]
        t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t)
        cookie.setExpires(t)
        self.response().addCookie(cookie)</pre>

Add this to your SitePage and you're all set. The cookie will last for 10 years, which is close enough to "forever" :-)

-- GeoffTalvola - 11 Dec 2001

Of course, you'll also have to call setPermanentCookie() at least once after you've added this to SitePage:

if not trans.request().hasCookie(yourCookieKey):
    self.setPermanentCookie(yourCookieKey, yourValue)

-- TavisRudd - 11 Dec 2001

RFC 2109 recommends expiring cookies by setting the "max-age" attribute to zero. Setting both "expires" and "max-age" is redundant, but apparently doesn't hurt and maintains compatibility. Add this as the second last line in deletePermanentCookie():

cookie.setMaxAge(0)

-- KenLalonde - 15 Jan 2002

Also, make sure that the servlet setting the cookie is in the same directory as where you plan to retrieve the cookie. So, if you set the cookie in http://myhost.com/webkit/users/ a servlet sitting at http://myhost.com/webkit will not be able to see the cookie. To override this, use cookie.setPath(). E.g. to set a cookie for the entire host, do:

cookie.setPath('/')

-- CostasMalamas - 17 Jan 2002