CBV加裝飾器的三種方式
阿新 • • 發佈:2022-12-10
CBV如何加裝飾器
# 先導包:from django.utils.decorators import method_decorator
# 方式一,加在某個具體的方法上,格式:@method_decorator(裝飾器名字)
# 方式二,加在類上,格式:@method_decorator(裝飾器名字,name='給某個方法加')
# 方式三,寫一個dispatch方法,加在其上,該類裡的方法都會被裝飾,格式:@method_decorator(login_auth)
CBV加裝飾器例項
from django.shortcuts import render, HttpResponse, redirect from django.views import View from functools import wraps # 給CBV加裝飾器,需要匯入以下模組 from django.utils.decorators import method_decorator # Create your views here. def login(request): if request.method == 'POST': username = request.POST.get('username') pwd = request.POST.get('pwd') if username == 'jason' and pwd == '123': request.session['name'] = 'jason' return redirect('/home/') return render(request, 'login.html') def login_auth(func): @wraps(func) def inner(request, *args, **kwargs): if request.session.get('name'): return func(request, *args, **kwargs) return redirect('/login/') return inner # 第二種加裝飾器的方法,@method_decorator(裝飾器名字,name='給某個方法加') # @method_decorator(login_auth, name='get') class MyHome(View): # 第三種加裝飾器的方法,該類裡的方法都會被裝飾 @method_decorator(login_auth) def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) # 第一種加裝飾器的方法,@method_decorator(裝飾器名字) # @method_decorator(login_auth) def get(self, request): """ 處理get請求 """ return HttpResponse('get') def post(self, request): """ 處理post請求 """ return HttpResponse('post')