在view中,可以采用一下方式屏蔽csrf
方式一
类的 dispatch 方法上使用 @csrf_exempt
from django.views.decorators.csrf import csrf_exempt
class MyView(View):
def get(self, request):
return HttpResponse("get")
def post(self, request):
return HttpResponse("post")
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
方式二
urls.py 中配置
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
import views
urlpatterns = [
url(r'^myview/$', csrf_exempt(views.MyView.as_view()), name='myview'),
]
对于rest-framework APIView 可以采用下面方式
override csrf验证
# views.py
from rest_framework.authentication import SessionAuthentication
from rest_framework.generics import GenericAPIView
class CsrfExemptSessionAuthentication(SessionAuthentication):
"""
去除 CSRF 检查
"""
def enforce_csrf(self, request):
return
class BaseAPIView(GenericAPIView):
#
authentication_classes = (CsrfExemptSessionAuthentication, )
permission_classes = (AllowAny, )