01-在類的 dispatch 方法上使用 @csrf_exempt
from django.views.decorators.csrf import csrf_exempt
class MyView(View):
def get(self, request):
return HttpResponse("hi")
def post(self, request):
return HttpResponse("hi")
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
02-在 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'),
]
03-重新改寫其中驗證 csrf 的方法
在之前,我們對於 csrf 的處理都是使用的 csrf_exempt ,現在我們的 API 都是使用 Router 來生成了。該怎么辦呢?
在 Django 中,一個請求在到達視圖之前,會先經過中間件的處理。在 DRF 中,所有的請求會先經過認證處理,如果請求認證通過,則會讓請求訪問視圖,如果認證不通過,請求就無法到達視圖。所以,我們采用的方法是重寫認證。
在 APIView 中,如果提供了 authentication_classes ,則會使用提供的認證后端來進行認證。如果沒有提供,則會使用默認的認證后端。有關的細節我們將會在之后的章節中討論,大家就先了解到這里。提供 csrf 驗證的是一個叫做 SessionAuthentication 的認證后端,我們需要重新改寫其中驗證 csrf 的方法。
# views.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
"""
去除 CSRF 檢查
"""
def enforce_csrf(self, request):
return
class MsgCodeViewSet(CreateModelMixin, viewsets.GenericViewSet):
serializer_class = MsgCodeSerializer
pagination_class = StandardResultsSetPagination
#
authentication_classes = (CsrfExemptSessionAuthentication, )
permission_classes = (AllowAny, )