Create a cookie that lasts until the browser is closed(Session Cookie?)

…衆ロ難τιáo~ 提交于 2020-01-14 19:43:26

问题


I am familiar with assigning, creating cookies in Python. But I am unsure how to create a cookie that will last until the current browser session is closed(so I have a very rudimentary way of telling when the user is returning to my website).

So which cookie header do I set to make sure the cookie will expire/delete when the browser is closed in Python? Do I use the SimpleCookie object or another object for this?

This thread says I set the cookie_lifetime flag/header in PHP, but what about for python? http://bytes.com/topic/php/answers/595383-how-declare-cookie-will-destroy-after-browser-closed

Would this create a cookie that expires on closing of the browser?

cookie  = Cookie.SimpleCookie()
cookie["test"] = "MYTEST"
cookie["test"]['expires'] = 0 # or shd I set the max-age header instead?
print str(cookie) + "; httponly"

回答1:


Just leave out the "expires" value altogether, i.e. don't set it to anything. See the Wikipedia entry for details:

Set-Cookie: made_write_conn=1295214458; path=/; domain=.foo.com

[...]

The second cookie made_write_conn does not have expiration date, making it a session cookie. It will be deleted after the user closes his/her browser

In Python:

In [11]: from Cookie import SimpleCookie

In [12]: c = SimpleCookie()

In [13]: c['test'] = 'MYTEST'

In [14]: print c
Set-Cookie: test=MYTEST



回答2:


Mack,

Your answer looks correct to me. Setting "expires" = 0 on the Morsel object should do what you want. Have you tested it?

Looks like max-age is not supported by IE:

http://mrcoles.com/blog/cookies-max-age-vs-expires/



来源:https://stackoverflow.com/questions/5670419/create-a-cookie-that-lasts-until-the-browser-is-closedsession-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!