开发者

Python: Persistent cookie, generate `expires` field

I'm trying to generate the text for a persistent cookie in a simple Python web application.

I'm having trouble finding a w开发者_JS百科ay 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


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 I am right, when using Cookie.SimpleCookie you can just specify the TTL in seconds for the expires field something like:

from Cookie import SimpleCookie

c = SimpleCookie()
c['sid'] = 'xxx'
c['sid']['path'] = '/'
c['sid']['expires'] = 12 * 30 * 24 * 60 * 60 #  1 year

The output of c.output()will return something like:

'Set-Cookie: sid=xxx; expires=Mon, 20 Jul 2015 14:42:35 GMT; Path=/'


Python's time.strftime() can format a given time for a cookie's expires according to RFC 6265:

import time
lease = 14 * 24 * 60 * 60  # 14 days in seconds
end = time.gmtime(time.time() + lease)
expires = time.strftime("%a, %d-%b-%Y %T GMT", end)
print(expires)

Output:

Tue, 23-Oct-2012 17:10:51 GMT

Time zones should be ignored, but since all the examples have "GMT", having it is probably safer.

Based upon Gareth Rees' answer.


I'm expanding a previous comment and a half answer to hopefully a usable answer.

This one produces to my knowledge a most correct and convenient cookie date format in a single fast function - accepted by any, even old and odd, browsers - accepts absolute & relative time:

import time
_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
_monthname = [None,
              'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
              'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def cookie_date(epoch_seconds=None, future=0):
    if not epoch_seconds:
        epoch_seconds = time.time()
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(epoch_seconds + future)
    return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \
           (_weekdayname[wd], day, _monthname[month], year, hh, mm, ss)

The function evolved from Cookie._getdate() / http.cookies._getdate(), which produces spaces instead of the convenient -'s (ok according to RFC, but not recognized by all browser). This function allows only relative timing and is an undocumented function. However it can be used by the also undocumented feature, that you can give integer seconds (but not float!) for the expires field in SimpleCookie morsels, which then are interpreted relative as seconds into the future / past:

cookie_morsel['expires'] = +3600    # 1h into future; 3600.0 doesn't work!

The frequently used time.strftime("%a, %d %b %Y %T GMT", t_expires) is questionable, because it depends on locale settings (%a, %d) and an OS-specific undocumented format spec (%T not understood on Windows e.g.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜