3

我有一个正在开发的网站,我想在 cookie 中存储一个值

这是一个数字,当用户访问网站时,我想知道他们上次访问时的数字是多少,所以我想有一个持久性 cookie 来存储当前值,当用户访问网站时,如果没有会话 cookie,则会话 cookie 获取持久性 cookie 的副本。这样,会话 cookie 始终具有上次访问的值。

即使我已将到期日期设置为从现在起一年

这是我的python代码:

persistentCookieKey = category + '_highest_id'
sessionCookieKey = 'session_' + persistentCookieKey + '_highest_id'

persistentCookieValue = request.get_cookie(persistentCookieKey)
if persistentCookieValue == None:
    persistentCookieValue = 0      # each time i restart my browser it comes through here!

sessionCookieValue = request.get_cookie(sessionCookieKey)
print 'persistentCookieValue:', persistentCookieValue
print 'sessionCookieValue:', sessionCookieValue

if sessionCookieValue == None:
    print 'session cookie not set, setting to:', persistentCookieValue
    sessionCookieValue = persistentCookieValue
    response.set_cookie(sessionCookieKey, str(persistentCookieValue))

print 'setting persistent cookie to value:', highestId
expireDate = date.today() + timedelta(days=365)
response.set_cookie(persistentCookieKey, str(highestId), expires=expireDate)

highestIdLastVisit = int(sessionCookieValue) 
4

1 回答 1

9

Bottle uses http://docs.python.org/library/cookie.html to implement cookie support. This implementation requires the expires parameter to be a string in the Wdy, DD-Mon-YY HH:MM:SS GMT format. Passing datetime or date objects fails silently.

I'll fix that in future versions of Bottle (hi, I'm the author) but for now I suggest using max_age instead.

Edit: Oh, and I just noticed it is also documented incorrectly. Sorry for that. Edit2: Fixed (in master)

于 2011-10-27T09:52:19.020 回答