django - 如何使用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
。这在我看来是矛盾的。
我错过了什么还是遇到了错误?
解决方案
推荐阅读
- python - 没有numpy,无法在python的二维矩阵中打印第一行或第一列名称。只会打印矩阵中的浮点数
- javascript - 无法读取未定义的属性“toString”,但函数接受我使用定义的 toString() 方法创建的类
- sql - 如何计算每条记录的空列
- java - 使用 Spring 表单更新后如何防止 POJO 中预先存在的对象引用变为空
- android-studio - 无法导入项目 - Android Studio 3.6.1
- java - 从 android 设备获取实际音量输出
- sql - 是否可以在本地连接上连接 Salesforce 和 SQL Server?
- kubernetes - Cloud Composer 实例节点和自动缩放
- javascript - React - 从 Mongo 渲染数据时未定义的属性
- python - 2位数年份校正后的Python熊猫跨世纪日期