一、用户认证装饰器:
使用装饰器,实现代码重用。
1、django自带的装饰器
# 一、自带的函数装饰器 from django.contrib.auth.decorators import login_required # 修饰函数 # 修改login_required默认的转向地址: 在Settings.py中添加LOGIN_URL = '转向地址' @login_required def index(request): name = request.COOKIES.get('username') # 读取客户端的用户名 pw = request.COOKIES.get('userpw') # 读取客户端的密码 auth_name = 'root' auth_pw = '123456' return render(request, '/index/') # 二、自带的类装饰器 from django.utils.decorators import method_decorator # Django的类中函数装饰 # ---------装饰到类中的函数----------- class Index(View): @method_decrator(auth) def dispantch(self, request, *args, **kwargs): return super(Index, self).dispatch(request, *args, **kwargs) def get(self, request): reuturn render(request, '/index/') # ---------装饰到类----------- @method_decrator(auth, name='dispatch') # auth:装饰器,name:装饰的类中的方法名 class Index(View): def get(self, request): reuturn render(request, '/index/')
2、CBV(Class Base Views)装饰器认证,使用类处理请求。
views.py
from django.http import HttpResponse from django.views import View # 方法一:类里面的所有方法都要加装饰 from django.utils.decorators import method_decorator # 导入Django装饰器 def auth(func): def inner_func(request, *args, **kwargs): name = request.COOKIES.get('username') # 读取客户端的用户名 pw = request.COOKIES.get('userpw') # 读取客户端的密码 auth_name = 'root' auth_pw = '123456' if name != auth_name and pw != auth_pw: return redirect('/login/') return inner_func class Index(View): @method_decorator(auth) # 进行装饰 def get(self, requet): return render(request, 'login.html') @method_decorator(auth) def post(self, request): return render(request, 'check.html') # 方式二:类继承装饰器,代码重用度高 class Auth(View): def dispatch(self, request, *args, **kwargs): # Auth继承View,向Dispatch添加了判断功能。 name = request.COOKIES.get('username') # 读取客户端的用户名 pw = request.COOKIES.get('userpw') # 读取客户端的密码 auth_name = 'root' auth_pw = '123456' if name != auth_name and pw != auth_pw: return redirect('/login/') return super(Auth, self).dispatch(self, request, *args, **kwargs) class Index(Auth): # 继承Auth def get(self, requet): return render(request, 'index.html') # 方式三:直接在类里面给dispatch添加功能,缺点是每个类都要重写 class Index(View): # 继承View def dispatch(self, request, *args, **kwargs): if not request.POST.get('username'): return redirect('/login/') return super(Index,self).dispatch(request, *args, **kwargs) def get(self, requet): return render(request, 'index.html')
3、FBV(Function Base Views)装饰器认证,使用函数处理请求。
from django.http import HttpResponse, redirect, render def auth(func): def inner_func(request, *args, **args): name = request.COOKIES.get('username') # 读取客户端的用户名 pw = request.COOKIES.get('userpw') # 读取客户端的密码 auth_name = 'root' auth_pw = '123456' if name != auth_name and pw != auth_pw: return redirect('/login/') return inner_func @auth def index(request): return render(request, 'index.html') @auth def details(request) return render(request, 'details.html')