如何使用Django在每个请求的浏览器关闭时设置cookie过期时间
我想让用户有可能决定使用持久会话。为此,我在登录页面中添加了一个如何使用Django在每个请求的浏览器关闭时设置cookie过期时间,django,session,cookies,django-middleware,Django,Session,Cookies,Django Middleware,我想让用户有可能决定使用持久会话。为此,我在登录页面中添加了一个记住我复选框;如果选中该复选框,则会话cookie将在1周后过期,如果未选中,cookie将在浏览器关闭时过期。 我在浏览器关闭时强制cookie过期时遇到一些问题。我正在使用request.session对象的set\u expiry方法。 文件规定: 在我看来,我正在设置request.session.set\u expiration(0),但是cookie过期总是使用setting.session\u cookie\u AG
记住我
复选框;如果选中该复选框,则会话cookie将在1周后过期,如果未选中,cookie将在浏览器关闭时过期。
我在浏览器关闭时强制cookie过期时遇到一些问题。我正在使用request.session
对象的set\u expiry
方法。
文件规定:
在我看来,我正在设置request.session.set\u expiration(0)
,但是cookie过期总是使用setting.session\u cookie\u AGE
值设置的
我尝试调试代码,似乎在SessionMiddleware
中调用request.session.get\u expiration\u age()
方法时,返回的值等于setting.session\u COOKIE\u age
,即使我将过期设置为0
我试图查看get\u expiration\u age
方法的文档,它说:
似乎,根据设置到期日
,如果我将到期日设置为0,cookie将在浏览器关闭时到期,但是根据获取到期日
,如果cookie设置为在浏览器关闭时到期,其到期日等于设置。会话cookie\u age
。在我看来,这似乎是一个矛盾
我是遗漏了什么还是遇到了错误
set_expiry(value)
Sets the expiration time for the session. You can pass a number of different values:
- If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes.
- If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer.
- If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.
- If value is None, the session reverts to using the global session expiry policy.
Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.
get_expiry_age()
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE.
This function accepts two optional keyword arguments:
- modification: last modification of the session, as a datetime object. Defaults to the current time.
- expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.