權限
DRF提供如下幾種常見權限:
IsAuthenticated, 認證通過
IsAdminUser, 管理員權限
IsAuthenticatedOrReadOnly, 登錄用戶增刪改 非登錄用戶只能查詢
AllowAny,無需認證(默認)
在rest_framework的APIView基礎類中,對認證與權限做了更高級的封裝,如下:
class APIView(View):# The following policies may be set at either globally, or per-view.authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSESpermission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
如果需要單獨設置
from django.conf import settings
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view,authentication_classes,permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status,generics,viewsets
#from rest_framework import permissions
from rest_framework.authentication import BasicAuthentication,SessionAuthentication,TokenAuthentication
from .models import Course
from .serializers import CourseSerializer
from rest_framework.views import APIView
fbv 方式
##函數式編程
@api_view(['GET','POST'])
@authentication_classes((BasicAuthentication,SessionAuthentication,TokenAuthentication))
@permission_classes((IsAuthenticated,))
def course_list(request):
cbv? gcbv viewsets 方式
# 類視圖 Class Based View
class CourseList(APIView):authentication_classes =
(BasicAuthentication,SessionAuthentication,TokenAuthentication)
permission_classes = ((IsAuthenticated))def get(self,request):print(self.request.user,self.request.auth)
自定義權限
?新建文件permissions.py
from rest_framework import permissionsclass IsOwnerReadOnly(permissions.BasePermission):#只允許對象的所有者能編輯def has_object_permission(self, request, view, obj):"""所有的request 都有讀權限:param request::param view::param obj::return:"""#if request.method in ("GET","HEAD","OPTIONS"):if request.method in permissions.SAFE_METHODS:return True#對象的所有這才有寫權限return obj.teacher == request.user #gcbv
加入到views.py 文件
class GCourseDetail(generics.RetrieveUpdateDestroyAPIView):queryset = Course.objects.all()serializer_class = CourseSerializerpermission_classes = (IsAuthenticated,IsOwnerReadOnly)# DRF 視圖集 viewsets
class CourseViewSet(viewsets.ModelViewSet):queryset = Course.objects.all()serializer_class = CourseSerializerpermission_classes = (IsAuthenticated, IsOwnerReadOnly)def perform_create(self, serializer):serializer.save(teacher= self.request.user)