drf06 認證Authentication 權限Permissions 限流Throttling

爲了方便接下來的學習,咱們建立一個新的子應用 fourpython

python manage.py startapp four

 

由於接下來的功能中須要使用到登錄功能,因此咱們使用django內置admin站點並建立一個管理員.django

python manage.py createsuperuser

建立管理員之後,訪問admin站點,先修改站點的語言配置服務器

settings.pysession

 

訪問admin 站點效果:app

 

 

1. 認證Authentication

rest_framework.settings裏面有默認的全局配置,不過咱們能夠在本身項目的setting.py文件中進行配置覆蓋學習

能夠在配置文件中(項目中的setting.py)配置全局默認的認證方案spa

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',  # session認證
        'rest_framework.authentication.BasicAuthentication',   # 基本認證
    )
}

 

也能夠在每一個視圖中經過設置authentication_classess屬性來設置(局部)rest

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
​
class ExampleView(APIView):
    # 類屬性
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    ...

 

認證失敗會有兩種可能的返回值:code

  • 401 Unauthorized 未認證對象

  • 403 Permission Denied 權限被禁止

 

 

 

2. 權限Permissions

權限控制能夠限制用戶對於視圖的訪問和對於具體數據對象的訪問。

  • 在執行視圖的dispatch()方法前,會先進行視圖訪問權限的判斷

  • 在經過get_object()獲取具體對象時,會進行模型對象訪問權限的判斷

使用

能夠在配置文件(項目中的setting.py)中全局設置默認的權限管理類,如

REST_FRAMEWORK = {
    ....
    
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

 

若是未指明,則採用以下(rest_framework.settings默認配置

'DEFAULT_PERMISSION_CLASSES': (
   'rest_framework.permissions.AllowAny',
)

 

也能夠在具體的視圖中經過permission_classes屬性來設置(局部),如

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
​
class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)
    ...

 

提供的權限

  • AllowAny 容許全部用戶

  • IsAuthenticated 僅經過認證的用戶

  • IsAdminUser 僅管理員用戶

  • IsAuthenticatedOrReadOnly 已經登錄認證的用戶能夠對數據進行增刪改操做,沒有登錄認證的只能查看數據。

舉例

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny,IsAdminUser,IsAuthenticated

class ExampleAPIView(APIView):
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]
    def get(self,request):
        print( type( request.user ) )
        return Response({"message":"ok"})

 

 

自定義權限

如需自定義權限,需繼承rest_framework.permissions.BasePermission父類,並實現如下兩個任何一個方法或所有

  • .has_permission(self, request, view)

    是否能夠訪問視圖, view表示當前視圖對象

  • .has_object_permission(self, request, view, obj)

    是否能夠訪問數據對象, view表示當前視圖, obj爲數據對象

例如:

在當前子應用下,建立一個權限文件permissions.py中聲明自定義權限類:

from rest_framework.permissions import BasePermission
​
class IsXiaoMingPermission(BasePermission):
    def has_permission(self, request, view):
        if( request.user.username == "xiaoming" ):
            return True
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import AllowAny,IsAdminUser,IsAuthenticated

from .permissions import IsXiaoMingAuthentication

class ExampleAPIView(APIView):
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsXiaoMingAuthentication]
    def get(self,request):
        print( type( request.user ) )
        return Response({"message":"ok"})

3. 限流Throttling

能夠對接口訪問的頻次進行限制,以減輕服務器壓力。

通常用於付費購買次數,投票等場景使用.

使用

能夠在配置文件中,使用DEFAULT_THROTTLE_CLASSESDEFAULT_THROTTLE_RATES進行全局配置,

REST_FRAMEWORK = {
    # 限流[全局]
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle', # 匿名用戶,遊客
        'rest_framework.throttling.UserRateThrottle'  # 已經通過認證的用戶
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '300/minute',
        'user': '1000/minute'
    },
}

 

DEFAULT_THROTTLE_RATES 可使用 second, minute, hourday來指明週期。

也能夠在具體視圖中經過throttle_classess屬性來配置,如

from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
​
class ExampleView(APIView):
    throttle_classes = (UserRateThrottle,)
    ...

 

可選限流類

1) AnonRateThrottle

限制全部匿名未認證用戶,使用IP區分用戶。

使用DEFAULT_THROTTLE_RATES['anon'] 來設置頻次

2)UserRateThrottle

限制認證用戶,使用User id 來區分。

使用DEFAULT_THROTTLE_RATES['user'] 來設置頻次

3)ScopedRateThrottle

限制用戶對於每一個視圖的訪問頻次,使用ip或user id。

例如:

class ContactListView(APIView):
    throttle_scope = 'contacts'
    ...
​
class ContactDetailView(APIView):
    throttle_scope = 'contacts'
    ...
​
class UploadView(APIView):
    throttle_scope = 'uploads'
    ...
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.ScopedRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        'contacts': '1000/day',
        'uploads': '20/day'
    }
}

 

實例

全局配置中設置訪問頻率

 'DEFAULT_THROTTLE_RATES': {
        'anon': '3/minute',
        'user': '10/minute'
    }
 

from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from rest_framework.throttling import UserRateThrottle
​
class StudentAPIView(RetrieveAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]
    throttle_classes = (UserRateThrottle,)
相關文章
相關標籤/搜索