django中间件:
- process_request
- process_view
- process_response
- process_exception
- process_render_template
中间件的作用:
权限
用户登录验证
CSRF token
process_view方法
检查视图是否被@csrf_exempt(免除csrf认证)
去请求体或cookie中获取token
FBV中加装饰器
from django.views.decorators.csrf import csrf_exempt, csrf_protect# 免除csrf token验证的装饰器@csrf_exemptdef users(request):pass# 全局不开启csrf,只有加此装饰器的才开启csrf token验证@csrf_protectdef groups(request):pass
CBV中加装饰器
from django.views.decorators.csrf import csrf_exempt, csrf_protectfrom django.utils.decorators import method_decorator# 方法一class StudentsView(View):# 把csrf_exempt当做参数传给method_decorator装饰器,并且只能加在dispatch方法上@method_decorator(csrf_exempt)def dispatch(self, request, *args, **kwargs):return super(StudentsView, self).dispatch(request, *args, **kwargs)def post(self, request, *args, **kwargs):return HttpResponse('POST')# 方法二@method_decorator(csrf_exempt, name='dispatch')class StudentsView(View):def dispatch(self, request, *args, **kwargs):return super(StudentsView, self).dispatch(request, *args, **kwargs)def post(self, request, *args, **kwargs):return HttpResponse('POST')
