Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Persistent cookie, generate `expires` field

Tags:

python

cookies

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

like image 941
Mike Avatar asked Jul 02 '11 12:07

Mike


People also ask

Do persistent cookies expire?

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.

How do you set the expiry period for a cookie object?

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.

How do I set a lifetime 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) );

What does Maxage in cookie mean?

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.


1 Answers

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=/
like image 159
zeekay Avatar answered Sep 23 '22 10:09

zeekay