I'm trying to generate the text for a persistent cookie in a simple Python web application.
I'm having trouble finding a way to generate the expires
field. The text format for the field is somewhat complicated, and I'd rather not write code to generate it myself.
Is there something in Python that will help? I've cooked at the docs for cookie
and cookielib
and they seem to handle a lot of the cookie business, except for generating the expires
field
Persistent CookiesThese cookies have an expiration date issued to it by the webserver. Basically, this type of cookie is saved on your computer so when you close it and start it up again, the cookie is still there. Once the expiration date is reached, it is destroyed by the owner.
Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.
All cookies expire as per the cookie specification, so this is not a PHP limitation. Use a far future date. For example, set a cookie that expires in ten years: setcookie( "CookieName", "CookieValue", time() + (10 * 365 * 24 * 60 * 60) );
Max-Age=<number> Optional. Indicates the number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both Expires and Max-Age are set, Max-Age has precedence.
I think you want to do something like this:
import Cookie, datetime, uuid
ck = Cookie.SimpleCookie()
ck['session'] = str(uuid.uuid4())
ck['session']['domain'] = 'foo.com'
ck['session']['path'] = '/'
expires = datetime.datetime.utcnow() + datetime.timedelta(days=30) # expires in 30 days
ck['session']['expires'] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
>>> print ck.output()
Set-Cookie: session=9249169b-4c65-4daf-8e64-e46333aa5577; Domain=foo.com; expires=Mon, 01 Aug 2011 07:51:53 GMT; Path=/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With