我正在尝试在简单的Python Web应用程序中为持久性cookie生成文本。
我无法找到生成expires
字段的方法。该字段的文本格式有点复杂,我宁愿不编写代码来自己生成它。
Python中有什么东西有帮助吗?我已经熟悉了cookie
和cookielib
的文档,除了生成expires
字段
答案 0 :(得分:11)
我想你想做这样的事情:
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=/
答案 1 :(得分:4)
如果我是对的,那么在使用Cookie.SimpleCookie
时,您只需指定到期字段的TTL,例如:
from Cookie import SimpleCookie
c = SimpleCookie()
c['sid'] = 'xxx'
c['sid']['path'] = '/'
c['sid']['expires'] = 12 * 30 * 24 * 60 * 60 # 1 year
c.output()
的输出将返回如下内容:
'Set-Cookie: sid=xxx; expires=Mon, 20 Jul 2015 14:42:35 GMT; Path=/'
答案 2 :(得分:0)
Python的time.strftime()
可以根据RFC 6265格式化Cookie的expires
给定时间:
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)
输出:
Tue, 23-Oct-2012 17:10:51 GMT
时区应该被忽略,但由于所有的例子都有“GMT”,所以它可能更安全。
答案 3 :(得分:0)
我正在扩展之前的评论和一半答案,希望可以得到一个可用的答案。
据我所知,这个在一个快速函数中产生了一个最正确和方便的cookie日期格式 - 被任何甚至旧的和奇数的浏览器所接受 - 接受绝对的&相对时间:
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)
该函数从Cookie._getdate()
/ http.cookies._getdate()
演变而来,它产生空格而不是方便的-
(根据RFC,但所有浏览器都无法识别)。此功能仅允许相对定时,并且是未记录的功能。然而,它也可以被未记录的特征使用,你可以为SimpleCookie
morsels中的expires字段提供整数秒(但不是float!),然后相对于未来/过去的秒数进行解释:
cookie_morsel['expires'] = +3600 # 1h into future; 3600.0 doesn't work!
经常使用的time.strftime("%a, %d %b %Y %T GMT", t_expires)
值得怀疑,因为它取决于区域设置(%a,%d)和特定于操作系统的未记录格式规范(例如,在Windows上无法理解%T)。