首页 > 解决方案 > 如何使用Django在每个请求的基础上在浏览器关闭时设置cookie过期

问题描述

我想让用户有可能决定进行持久会话。为此,我Remember me在登录页面中添加了一个复选框;如果选中复选框,则会话 cookie 将在 1 周后过期,如果未切换,则 cookie 将在浏览器关闭时过期。我在浏览器关闭时遇到一些强制 cookie 过期的问题。我正在使用对象的set_expiry方法request.session。文档说明了这一点: https ://docs.djangoproject.com/en/3.2/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry

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.

在我看来,我正在设置request.session.set_expiry(0),但始终使用该setting.SESSION_COOKIE_AGE值设置 cookie 过期时间。

我尝试调试代码,似乎当在request.session.get_expiry_age()中调用该方法时SessionMiddleware,返回的值等于setting.SESSION_COOKIE_AGE,即使我将过期设置为 0。

我试图查看该get_expiry_age方法的文档,它说: https ://docs.djangoproject.com/en/3.2/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.get_expiry_age

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.

看来,根据set_expiry,如果我将过期时间设置为 0,cookie 将在浏览器关闭时过期,但根据get_expiry_date,如果 cookie 设置为在浏览器关闭时过期,其过期时间等于settings.SESSION_COOKIE_AGE。这在我看来是矛盾的。

我错过了什么还是遇到了错误?

标签: djangosessioncookiesdjango-middleware

解决方案


推荐阅读