Django笔记——csrf认证
FBV模式
csrf免认证
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # 该函数无需认证
def users(request):
user_list = ['张三','李四']
res = json.dumps(user_list)
return HttpResponse(res)
csrf单独认证
from django.views.decorators.csrf import csrf_protect
@csrf_protect # 该函数需认证
def users(request):
user_list = ['张三','李四']
res = json.dumps(user_list)
return HttpResponse(res)
CBV模式
添加csrf免认证
方式一:在类视图上面添加@method_decorator(csrf_exempt, name=‘dispatch’)
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt,name='dispatch')
class StudentsView(View):
def get(self,request,*args,**kwargs):
return HttpResponse('GET')
def post(self, request, *args, **kwargs):
return HttpResponse('POST')
def put(self, request, *args, **kwargs):
return HttpResponse('PUT')
def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
方式二:在类视图中的dispatch()方法前面添加@method_decorator(csrf_exempt)
from django.views.decorators.csrf import csrf_exempt,csrf_protect
from django.utils.decorators import method_decorator
class StudentsView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(StudentsView,self).dispatch(request, *args, **kwargs)
def get(self,request,*args,**kwargs):
print('get方法')
return HttpResponse('GET')
def post(self, request, *args, **kwargs):
return HttpResponse('POST')
def put(self, request, *args, **kwargs):
return HttpResponse('PUT')
def delete(self, request, *args, **kwargs):
return HttpResponse('DELETE')
还没有评论,来说两句吧...