1、在對應的視圖函數里增加認證(局部起作用,不全局生效)
導入類:
from rest_framework.authentication import (
? ? BasicAuthentication,
? ? SessionAuthentication,
)
from rest_framework.permissions import IsAuthenticated, AllowAny
2、基于第八節內容增加以下權限設置內容
#定義認證類型
authentication_classes = [SessionAuthentication]
#定義權限限制
permission_classes = [IsAuthenticated]
備注說明:
AllowAny? 允許所有用戶,默認權限
IsAuthenticated? 僅通過登錄認證的用戶
IsAdminUser 僅管理員用戶
IsAuthenticatedOrReadOnly? 已經登錄認證的用戶可以對數據進行CRUD操作,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 沒有登錄認證的用戶,只能查看數據
3、完整code
from django.shortcuts import render, HttpResponse
from rest_framework.response import Response
from rest_framework.decorators import actionfrom rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,
)
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializersfrom rest_framework.authentication import (BasicAuthentication,SessionAuthentication,
)
from rest_framework.permissions import IsAuthenticated, AllowAnyfrom .models import *
from api.serializer import *# 這種寫法實現所有的增刪改查,不能夠單獨進行操作
# class Linkapi(ModelViewSet):
# 不僅可以實現所有的增刪改查,而且可以單獨也可以全部包含增刪改查
class Linkapi(GenericViewSet,ListModelMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,
):queryset = Link.objects.all()serializer_class = LinkSerializerauthentication_classes = [SessionAuthentication]permission_classes = [IsAuthenticated]# 在原有的二級路由中自定義添加三級路由路徑# 訪問路徑/api/linkapi/{pk}/login/@action(methods=["get", "POST"],detail=True,url_path="login",)def login(self, request, pk):queryset = self.get_queryset()serializer = self.get_serializer(queryset, many=True)return Response(serializer.data)# detail為false表示路徑名格式應該為/api/linkapi/get_new_5/@action(methods=["get",],detail=False,)def get_new_2(self, request):obj = Link.objects.all().filter()[:2]serializer = self.get_serializer(instance=obj, many=True)return Response(serializer.data)
4、測試
5、僅允許查詢,其他方式請求未授權不能訪問
導入包
from rest_framework.permissions import (
? ? IsAuthenticated,
? ? AllowAny,
? ? IsAuthenticatedOrReadOnly,
)
修改視圖類內容
# IsAuthenticated 授權登錄后可以訪問
# IsAuthenticatedOrReadOnly ?只允許查詢
permission_classes = [IsAuthenticatedOrReadOnly]
6、?