Django的CSRF认证是在process_view的时候认证的,它做了两件事
1. 检查视图是否被@csrf_exempt函数装饰器装饰
2. 去请求体或者cookie中获取token,进行校验
关于@csrf_exempt
1. 如果视图被此装饰器装饰,那么该视图就不会进行csrf验证。
2. @csrf_protect装饰器与其相反, 如果被@csrf_protect装饰,则必须进行csrf认证
3. 不能直接用于类视图。 类视图使用方法:在类视图前加@method_decorator(csrf_exempt, name='dispatch'),或者重写dispatch方法,并为其加上@method_decorator(csrf_exempt)
from django.shortcuts import render, HttpResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt class MyBaseView(object): def dispatch(self, request, *args, **kwargs): print('before') ret = super(MyBaseView, self).dispatch(request, *args, **kwargs) print('after') return ret @method_decorator(csrf_exempt, 'dispatch') # 本类视图不校验csrf class StudentsView(MyBaseView, View): def get(self, request, *args, **kwargs): return HttpResponse('GET') def post(self, request, *args, **kwargs): return HttpResponse('POST') def delete(self, request, *args, **kwargs): return HttpResponse('DELETE') def put(self, request, *args, **kwargs): return HttpResponse('PUT')