rest_framework学习之认证 权限
权限
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)