使用Django停用匿名用户Cookie [英] Disable anonymous user cookie with Django

查看:513
本文介绍了使用Django停用匿名用户Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的网站使用django auth,需要安装会话中间件。

I use django auth for my website, which needs to have the session middleware installed.

Django会话中间件总是添加会话cookie,即使对于匿名用户未经认证)。

Django session middleware always adds a session cookie, even for anonymous users (users that are not authenticated). When they authenticate the cookie is replaced by another one indicating the user is logged-in.

我想禁用匿名用户cookie以用于缓存目的(varnish)。

I want to disable the anonymous user cookie for caching purposes (varnish).

有没有办法在不删除会话中间件的情况下禁用匿名用户Cookie,这是应用程序使用auth所必需的?

Is there a way to disable anonymous user cookies without removing session middleware which is necessary for apps using auth?

推荐答案

会话数据在 process_response SessionMiddleware 中的cookie中设置。此函数不使用任何设置或 request.user ,因此您无法在此方法内部了解用户是登录用户还是匿名用户。

Session data is set in the cookie in the process_response of SessionMiddleware. This function doesn't use any setting or request.user, so you do not have any way of knowing inside this method whether the user is a logged in user or an anonymous user. So, you can't disable sending the session cookie to the browser.

但是如果你想要这个功能,你可以将 SessionMiddleware ,并覆盖 process_response

However if you want this functionality then you can subclass SessionMiddleware and overide process_response.

from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings

class NewSessionMiddleware(SessionMiddleware):

    def process_response(self, request, response):
        response = super(NewSessionMiddleware, self).process_response(request, response)
        #You have access to request.user in this method
        if not request.user.is_authenticated():
            del response.cookies[settings.SESSION_COOKIE_NAME]
        return response

您可以使用 NewSessionMiddleware 代替 SessionMiddleware

MIDDLEWARE_CLASSES = (
  'django.middleware.common.CommonMiddleware',
  'myapp.middleware.NewSessionMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.middleware.doc.XViewMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
)

这篇关于使用Django停用匿名用户Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆