一、使用装饰器校验登录状态
1.装饰器
(1)外层函数内嵌内层函数
(2)外层函数返回内层函数
(3)内层函数调用外层函数的参数
def is_login(func):
def check_status(request):
pass
return check_status
2.定义装饰器
from django.http import HttpResponse, HttpResponseRedirect
from user.models import MyUser, TokenUser
def is_login(func):
def check_status(request):
token = request.COOKIES.get('token')
if token:
token_user = TokenUser.objects.filter(token=token).first()
if token_user:
# return func(request)表示继续执行被is_login装饰的函数
return func(request)
else:
return HttpResponseRedirect('/login/')
else:
return HttpResponseRedirect('/login/')
return check_status
@is_login
def my_index(request):
if request.method == 'GET':
return render(request, 'index.html')
二、使用中间件校验登录状态
1.修改settings.py配置文件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'utils.middle_ware.LoginStatusMiddleware',
]
2.定义中间件
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse, HttpResponseRedirect
from user.models import TokenUser
class LoginStatusMiddleware(MiddlewareMixin):
def process_request(self, request):
# 在访问登录和注册页面的时候,不需要做以下的登录校验功能
if request.path in ['/login/', '/register/']:
return None
# 登录校验
token = request.COOKIES.get('token')
if token:
token_user = TokenUser.objects.filter(token=token).first()
if token_user:
return None
else:
return HttpResponseRedirect('/login/')
else:
return HttpResponseRedirect('/login/')
def process_response(self, request, response):
return response
三、session实现登录和校验登录状态
1.实现登录操作
(1)向cookie中设置session_id值,value为随机字符串
(2)向django_session表中存入session_id值,并保存键值对
from django.http import HttpResponse, HttpResponseRedirect
from user.models import MyUser, TokenUser
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
# 1.获取登录提交的用户名和密码
username = request.POST.get('username')
password = request.POST.get('password')
# 2.查询数据库中用户名和密码对应的用户对象
user = MyUser.objects.filter(username=username, password=password).first()
if not user:
err = '用户名或者密码错误!'
return render(request, 'login.html', {'err': err})
# 3.使用session实现登录操作
request.session['user_id'] = user.id
# 4.跳转到首页
res = HttpResponseRedirect('/my_index/')
return res
2.校验登录状态
session校验
(1)获取cookie中的session值
(2)查询django_session表中的session_key字段,查询到数据,则获取session_data中存入的键值对
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse, HttpResponseRedirect
from user.models import TokenUser, MyUser
class LoginStatusMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.path in ['/login/', '/register/']:
return None
user_id = request.session.get('user_id')
if user_id:
# 向request.user中赋值,赋值为当前登录系统的用户对象
user = MyUser.objects.get(pk=user_id)
request.user = user
return None
else:
return HttpResponseRedirect('/login/')
def process_response(self, request, response):
return response
3.注销
(1)删除cookie中的session_id值
(2)或者删除django_session表中的数据
def logout(request):
# 方法1:删除客户端cookie中的数据以及django_session表中的数据
request.session.flush()
# 方法2:删除django_session表中的数据
# request.session.delete(request.session.session_key)
# 方法3:删除session_data中登录成功后设置的键值对
# del request.session['user_id']
return HttpResponseRedirect('/login/')