【问题标题】:Setting expiring cookies in Plone在 Plone 中设置过期 cookie
【发布时间】:2012-03-12 14:42:23
【问题描述】:

我想在未来几个小时内设置一个过期时间的 cookie

已经存在一个显示如何设置 cookie 的问题:

How do you get and set cookies in Zope and Plone?

...但我没有找到如何以“正确方式”使用 Zope 生成 RFC 822 时间戳的示例。看起来其他框架在内部从日期时间生成时间戳。

还有可能让 cookie 在浏览器关闭时过期吗?这个是没有有效期的吗?

【问题讨论】:

    标签: cookies plone zope


    【解决方案1】:

    您可以查看这两个问题的答案,以了解如何生成有效的RFC 822 date time 值。

    1. What is the best way to convert a zope DateTime object into Python datetime object?
    2. How do I convert RFC822 to a python datetime object?

    要创建一个在浏览器关闭后立即过期的 cookie,只需创建一个没有过期日期的 cookie。这将生成一个会话 cookie,一旦浏览器会话过期,该 cookie 就会过期。

    【讨论】:

    • 使用 email.Utils.formatdate(seconds, usegmt=True) 比使用自己的 RFC 822 格式化例程更安全。
    【解决方案2】:

    您可以通过在 cookie 上设置 expires 属性来将 cookie 设置为在将来的某个日期过期。这应该是使用 Python 标准库中的 email.Utils 模块中的 formatdate 生成的 RFC822 值。

    import time
    from email.Utils import formatdate
    expiration_seconds = time.time() + (5*60*60) # 5 hours from now
    expires = formatdate(expiration_seconds, usegmt=True) 
    response.setCookie('cookie_name', 'value', path='/', expires=expires)
    

    (Internet Explorer 不支持 cookie 规范建议的 max-age 属性。)

    如果您希望在关闭浏览器时清除 cookie,请不要设置 expires 值。

    注意。请务必始终设置您的 cookie 有效的路径,否则它只会在您设置它的页面上有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多