Disable anonymous user cookie with Django

蓝咒 提交于 2019-11-30 13:06:20

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.

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

And you can use your NewSessionMiddleware in place of 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',
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!