類視圖添加裝飾器
阿新 • • 發佈:2018-09-10
pos ren pan ora *args tro quest 就是 執行
from django.utils.decorators import method_decorator
1. 加在CBV視圖的get或post方法上
1 from django.utils.decorators import method_decorator
2
3
4 class HomeView(View):
5
6 def dispatch(self, request, *args, **kwargs):
7 return super(HomeView, self).dispatch(request, *args, **kwargs)
8
9 def get(self, request):
10 return render(request, "home.html")
11
12 @method_decorator(check_login)
13 def post(self, request):
14 print("Home View POST method...")
15 return redirect("/index/")
2. 加在dispatch方法上
1 from django.utils.decorators import method_decorator
2
3
4 class HomeView(View):
5
6 @method_decorator(check_login)
7 def dispatch(self, request, *args, **kwargs):
8 return super(HomeView, self).dispatch(request, *args, **kwargs)
9
10 def get(self, request):
11 return render(request, "home.html")
12
13 def post(self, request):
14 print("Home View POST method...")
15 return redirect("/index/")
因為CBV中首先執行的就是dispatch方法,所以這麽寫相當於給get和post方法都加上了登錄校驗。
3. 直接加在視圖類上,但method_decorator必須傳 name 關鍵字參數
如果get方法和post方法都需要登錄校驗的話就寫兩個裝飾器。
1 from django.utils.decorators import method_decorator
2
3 @method_decorator(check_login, name="get")
4 @method_decorator(check_login, name="post")
5 class HomeView(View):
6
7 def dispatch(self, request, *args, **kwargs):
8 return super(HomeView, self).dispatch(request, *args, **kwargs)
9
10 def get(self, request):
11 return render(request, "home.html")
12
13 def post(self, request):
14 print("Home View POST method...")
15 return redirect("/index/")
CSRF Token相關裝飾器在CBV只能加到dispatch方法上,或者加在視圖類上然後name參數指定為dispatch方法。
備註:
- csrf_protect,為當前函數強制設置防跨站請求偽造功能,即便settings中沒有設置全局中間件。
- csrf_exempt,取消當前函數防跨站請求偽造功能,即便settings中設置了全局中間件。
1 from django.views.decorators.csrf import csrf_exempt, csrf_protect 2 from django.utils.decorators import method_decorator 3 4 5 class HomeView(View): 6 7 @method_decorator(csrf_exempt) 8 def dispatch(self, request, *args, **kwargs): 9 return super(HomeView, self).dispatch(request, *args, **kwargs) 10 11 def get(self, request): 12 return render(request, "home.html") 13 14 def post(self, request): 15 print("Home View POST method...") 16 return redirect("/index/")
或者:
1 from django.views.decorators.csrf import csrf_exempt, csrf_protect 2 from django.utils.decorators import method_decorator 3 4 5 @method_decorator(csrf_exempt, name=‘dispatch‘) 6 class HomeView(View): 7 8 def dispatch(self, request, *args, **kwargs): 9 return super(HomeView, self).dispatch(request, *args, **kwargs) 10 11 def get(self, request): 12 return render(request, "home.html") 13 14 def post(self, request): 15 print("Home View POST method...") 16 return redirect("/index/")
類視圖添加裝飾器