如果您django_session
在登录时手动添加一行,则在django.contrib.auth.logout()
, request.session.flush()
) 函数只会session_key
从表中删除与当前会话键具有相同主键的行django_session
。
request.session.flush()
用于确保不能从用户的浏览器再次访问之前的会话数据。它基本上做了两件事:
- 从数据库中删除当前会话数据(或缓存,取决于您为会话后端选择哪一个)。
- 重新生成在 cookie 中发送回用户的会话密钥值。
Django 源代码django.contrib.auth.logout()
:
def logout(request):
"""
Removes the authenticated user's ID from the request and flushes their
session data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if hasattr(user, 'is_authenticated') and not user.is_authenticated():
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user)
request.session.flush()
if hasattr(request, 'user'):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()
基于数据库的会话的删除方法:
def delete(self, session_key=None):
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
try:
Session.objects.get(session_key=session_key).delete()
except Session.DoesNotExist:
pass
要删除手动添加的行,您可以利用 Django 信号django.contrib.auth.signals.user_logged_out
在用户注销时删除行。