django中使用中间件保护和跳过csrf校验

基于CBV:

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
# Create your views here.
from django.views import View
@method_decorator(csrf_exempt,name='dispatch')
class asset(View):
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)
    def get(self,request):
        return HttpResponse('get请求')
    def post(self,request):
        print(request.POST)
        return HttpResponse('post请求')

基于FBV:

@csrf_protect
def asset1(request):
    return HttpResponse('ok')

 

PS:如果在中间件中注释了全局的csrf,那么可以使用csrf_protect来保护csrf

    如果中间件中启用了全局的csrf,那么可以使用csrf_except来跳过csrf校验

原文地址:https://www.cnblogs.com/duoduoyichen/p/11160559.html