为 Django 中的选定页面禁用 sessions/cookies

Disable sessions/cookies for selected pages in Django

在我的网站上,只有在管理部分进行身份验证才需要 cookie 和会话。对于所有其他网址,我不想存储 cookie 或 运行 会话中间件,因为它会在每个 http 请求上创建不必要的数据库 read/write。

有没有办法为选定页面禁用会话中间件,而身份验证中间件不会抱怨缺少会话中间件?

It creates an unnecessary DB read/write on every http request.

这是不正确的。 Django 仅在您尝试向其写入内容时才创建会话 - 在此之前不会创建会话,也不会设置会话 cookie。来自 documentation:

By default, Django only saves to the session database when the session has been modified.

Note that the session cookie is only sent when a session has been created or modified. If SESSION_SAVE_EVERY_REQUEST is True, the session cookie will be sent on every request.

SESSION_SAVE_EVERY_REQUEST 默认为 False)。

因此对于您所描述的那种情况,永远不会为不访问管理员的用户创建会话,并且不会有数据库开销。唯一的小开销是检查会话 cookie 的中间件。