drf的三大認證


三大認證任務分析

  • 認證模塊:校驗用戶是是否登陸
self.perform_authentication(request)
  • 權限模塊:校驗用戶是否擁有權限
self.check_permissionsn(request)
  • 頻率模塊:訪問接口的次數在設定的時間范圍內是否過快(配置訪問頻率、緩存計次、超次后需要等待的時間)
self.check_throttles(request)

auth組件的認證權限六表

也就是基於角色的訪問控制:基於角色的訪問控制(RBAC)是實施面向企業安全策略的一種有效的訪問控制方式。

Django框架采用的是RBAC認證規則,RBAC認證規則通常會分為 三表規則、五表規則,Django采用的是六表規則

  • 三表:用戶表、角色表、權限表
  • 五表:用戶表、角色表、權限表、用戶角色關系表、角色權限關系表
  • 六表:用戶表、角色表、權限表、用戶角色關系表、角色權限關系表、用戶權限關系表

舉個栗子:看圖說話

所以我們需要建立關聯表(python中是六張表)

我們在實際開發中可能要重寫六表

在python中的數據庫中會有這六張表eg:用戶表中會有用戶名、密碼、是否是超級管理員、是否是活躍用戶等

auth_permission中的Content_type:給Django中的所有模塊中的所有表進行編號存儲到Content_type中

# 應用一:權限表的權限是操作表的,所有在權限表中有一個content_type表的外鍵,標識該權限具體操作的是哪張表
# 應用二:價格策略

"""
Course:
name、type、days、price、vip_type
基礎	免費課  7		0
中級	學位課	 180	69
究極	會員課	 360    	 至尊會員
以上的這張課表有大量字段重復以及空值非常麻煩,所以我們需要拆表甚至用到content_type

Course:
name、type、days、content_type_id
基礎	免費課  7	  null
中級	學位課	 180   1
究極	會員課	 360   2

content_type表(Django提供)
id、app_label、model
1	app01	 course_1
2	app01	 course_2

app01_course_1  #價格策略一表(字段不一樣)
id、price

app01_course_2  #價格策略二表(字段不一樣)
id vip_type

"""

自定義User表分析

注意:

1)auth認證6表必須在第一次數據庫遷移前確定,第一次數據庫遷移完成

2)完成數據庫遷移,出現了auth的用戶遷移異常,需要刪除的數據庫遷移文件有User表所在的自定義應用下的、admin組件下的、auth組件下的表刪除了

源碼分析

認證與權限工作原理

源碼分析

APIView下的dispatch方法中的initial方法中含有三大認證:

self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)

APIView下有配置視圖類的三大認證

auth組件的校驗規則有三點如下圖:

session認證是從cookies中去拿

認證模塊工作原理

  • 繼承BaseAuthentication類,重寫authenticate方法
  • 認證規則(authenticate方法實現體):
    • 沒有攜帶認證信息,直接返回None => 游客
    • 有認證信息,校驗失敗,拋異常 => 非法用戶
    • 有認證信息,校驗出User對象 => 合法用戶

權限模塊工作原理

  • 繼承BasePermission類,重寫has_permission方法
  • 權限規則(has_permission方法實現體):
    • 返回True,代表有權限
    • 返回False,代表無權限

admin關聯自定義用戶表

自定義認證、權限類

admin中的操作

用戶群查接口權限分析

urls.py:

url(r'^users/$', views.UserListAPIView.as_view())  #群查接口

views.py:

from rest_framework.generics import ListAPIView
from . import models, serializers
# 查看所有用戶信息,前提:必須是登錄的超級管理員
#這里要分析Token源碼
from utils.authentications import TokenAuthentication  
from utils.permissions import SuperUserPermission
class UserListAPIView(ListAPIView):
    # 同電商網站,多接口是不需要登錄的,少接口需要登錄,使用在需要登錄的接口中完成局部配置,進行局部接口校驗
    authentication_classes = [TokenAuthentication]
    permission_classes = [SuperUserPermission]

    queryset = models.User.objects.filter(is_active=True, is_superuser=False).all()
    serializer_class = serializers.UserModelSerializer

    def get(self, request, *args, **kwargs):   #如果你想重寫狀態碼
        response = self.list(request, *args, **kwargs)
        return APIResponse(data=response.data)

serializer.py中

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, ValidationError
from . import models
class UserModelSerializer(ModelSerializer):
    class Meta:
        model = models.User
        fields = ('username', 'email', 'mobile')  #還有一些信息你也可以提供

附:

自定義認證類

views.py中

class UserListAPIView(ListAPIView):
    # 同電商網站,多接口是不需要登錄的,少接口需要登錄,使用在需要登錄的接口中完成局部配置,進行局部接口校驗
    authentication_classes = [TokenAuthentication]
    permission_classes = [SuperUserPermission]
	pass
# 登錄接口:如果是超級管理員登錄,返回一個可以交易出超級管理員的token字符串
# 只要有用戶登錄,就可以返回一個與登錄用戶相關的token字符串 => 返回給前台 => 簽發token => user_obj -> token_str

新建一個文件authentications.py

#自定義認證類
"""
認證模塊工作原理
1)繼承BaseAuthentication類,重寫authenticate方法
2)認證規則(authenticate方法實現體):
    沒有攜帶認證信息,直接返回None => 游客
    有認證信息,校驗失敗,拋異常 => 非法用戶
    有認證信息,校驗出User對象 => 合法用戶
"""

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed


class TokenAuthentication(BaseAuthentication):
    prefix = 'Token'   #自定義一個反爬

    def authenticate(self, request):
        # 拿到前台的token
        auth = request.META.get('HTTP_AUTHORIZATION')
        # 沒有返回None,有進行校驗
        if not auth:
            return None
        auth_list = auth.split()

        if not (len(auth_list) == 2 and auth_list[0].lower() == self.prefix.lower()):
            raise AuthenticationFailed('非法用戶')

        token = auth_list[1]

        # 校驗算法
        user = _get_obj(token)
        # 校驗失敗拋異常,成功返回(user, token)
        return (user, token)


# 校驗算法(認證類)與簽發算法配套
"""
拆封token:一段 二段 三段
用戶名A:b64decode(一段)
用戶主鍵B:b64decode(二段)
碰撞解密:md5(用戶名A+用戶主鍵B+服務器秘鑰) == 三段
服務器秘鑰是一個固定的字符串在settings中
"""
import base64, json, hashlib
from django.conf import settings
from api.models import User


def _get_obj(token):
    token_list = token.split('.')
    if len(token_list) != 3:
        raise AuthenticationFailed('token異常')
    username = json.loads(base64.b64decode(token_list[0])).get('username')
    pk = json.loads(base64.b64decode(token_list[1])).get('pk')

    md5_dic = {
        'username': username,
        'pk': pk,
        'key': settings.SECRET_KEY
    }

    if token_list[2] != hashlib.md5(json.dumps(md5_dic).encode()).hexdigest():
        raise AuthenticationFailed('token內容異常')

    user_obj = User.objects.get(pk=pk, username=username)
    return user_obj

認證類的認證核心規則

def authenticate(self, request):
    token = get_token(request)
    try:
        user = get_user(token)  # 校驗算法
    except:
        raise AuthenticationFailed()
    return (user, token)

自定義權限類

新建一個文件夾Permission.py

# 自定義權限類
"""
權限模塊工作原理
1)繼承BasePermission類,重寫has_permission方法
2)權限規則(has_permission方法實現體):
    返回True,代表有權限
    返回False,代表無權限
"""
from rest_framework.permissions import BasePermission
class SuperUserPermission(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_superuser

前后台分離登陸接口

views.py

# 登錄接口:如果是超級管理員登錄,返回一個可以交易出超級管理員的token字符串
# 只要有用戶登錄,就可以返回一個與登錄用戶相關的token字符串 => 返回給前台 => 簽發token => user_obj -> token_str

from rest_framework.generics import GenericAPIView
class LoginAPIView(APIView):
    # 登錄接口一定要做:局部禁用 認證 與 權限 校驗
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginModelSerializer(data=request.data)
        # 重點:校驗成功后,就可以返回信息,一定不能調用save方法,因為該post方法只完成數據庫查操作
        # 所以校驗會得到user對象,並且在校驗過程中,會完成token簽發(user_obj -> token_str)
        serializer.is_valid(raise_exception=True)
        return APIResponse(data={
            'username': serializer.user.username,
            'token': serializer.token
        })

serializers.py

from django.contrib.auth import authenticate
class LoginModelSerializer(ModelSerializer):
    # username和password字段默認會走系統校驗,而系統的post請求校驗,一定當做增方式校驗,所以用戶名會出現 重復 的異常
    # 所以自定義兩個字段接收前台的賬號密碼
    usr = serializers.CharField(write_only=True)
    pwd = serializers.CharField(write_only=True)
    class Meta:  #非標准接口下面的反序列化
        model = models.User
        fields = ('usr', 'pwd')
    def validate(self, attrs):    #全局鈎子
        usr = attrs.get('usr')
        pwd = attrs.get('pwd')
        try:
            user_obj = authenticate(username=usr, password=pwd)
        except:
            raise ValidationError({'user': '提供的用戶信息有誤'})
        # 拓展名稱空間
        self.user = user_obj
        # 簽發token
        self.token = _get_token(user_obj)
        return attrs

# 自定義簽發token
# 分析:拿user得到token,后期還需要通過token得到user
# token:用戶名(base64加密).用戶主鍵(base64加密).用戶名+用戶主鍵+服務器秘鑰(md5加密)
# eg: YWJj.Ao12bd.2c953ca5144a6c0a187a264ef08e1af1

頻率認證源碼分析

APIView ---dispatch方法---self.initial(request, *args, **kwargs)---self.check_throttles(request)
  #重新訪問這個接口的時候,都會重新調用這個方法,每次訪問都會throtttle_durations=[]置空
    def check_throttles(self, request):
        """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """
        #比如一分鍾只能訪問三次,第一,二,三次訪問的時候都沒有限制,第四次訪問就會制
        #限次的持續時間,還有多少秒才能接着訪問這個接口
        throtttle_durations=[]
        # self.get_throttles()全局或局部配置的類
        for throttle in self.get_throttles():
            #allow_request允許請求返回True,不允許就返回False,為false時成立,
            if not throttle.allow_request(request, self):
                #throttle.wait()等待的限次持續時間
                self.throttled(request, throttle.wait())
        # 第四次限制,有限制持續時間才會走這部 
        if throttle_durations:
            durations = [
                duration for duration in throttle_durations
                if duration is not None
            ]
            duration = max(durations, default=None)
            self.throttled(request, duration)
這說明我們自定義類要重寫allow_request(request, self)和wait(),因為throttle調用了
點擊 self.get_throttles()查看
    def get_throttles(self):
        """ Instantiates and returns the list of throttles that this view uses. """
        return [throttle() for throttle in self.throttle_classes]

點擊 self.throttle_classes
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES

throttle_classes跟之前一樣可局部配置throttle_classes=[] ,可全局配置settings文件中配置

到drf資源文件settings.py文件中的APISettings類中查看默認配置:ctrl+f鍵查找DEFAULT_THROTTLE_CLASSES
'DEFAULT_THROTTLE_CLASSES': [],#所以說任何接口都可以無限次訪問

回到def check_throttles(self, request):pass 中的allow_request方法進行思考,首先去獲取下多長時間能夠訪問多少次,然后就是訪問一次就計數一次,超次了就不能訪問了,所以要去獲取時間,在一定的時間內不能超次,如果在一定的時間內超次了就調用wait,倒計時多久才能再次訪問,
allow_request其實就是先獲取到多長時間訪問多少次,每來一次請求把當前的時間和次數保存着,如果它兩的間隔時間足夠大,就重置次數為0,如果間隔時間較小就次數累加

找到drf資源文件throttling.py (有以下類)
AnonRateThrottle(SimpleRateThrottle)
BaseThrottle(object)
ScopedRateThrottle(SimpleRateThrottle)
SimpleRateThrottle(BaseThrottle)
UserRateThrottle(SimpleRateThrottle)

我們自定義的類有可能繼承BaseThrottle,或SimpleRateThrottle
class BaseThrottle(object):
    """ Rate throttling of requests. """
    #判斷是否限次:沒有限次可以請求True,限次就不可以請求False
    def allow_request(self, request, view):
        """ Return `True` if the request should be allowed, `False` otherwise. """
        #如果繼承 BaseThrottle,必須重寫allow_request
        raise NotImplementedError('.allow_request() must be overridden')

    def get_ident(self, request):
        """ Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR if present and number of proxies is > 0. If not use all of HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. """
        xff = request.META.get('HTTP_X_FORWARDED_FOR')
        remote_addr = request.META.get('REMOTE_ADDR')
        num_proxies = api_settings.NUM_PROXIES
    
        if num_proxies is not None:
            if num_proxies == 0 or xff is None:
                return remote_addr
            addrs = xff.split(',')
            client_addr = addrs[-min(num_proxies, len(addrs))]
            return client_addr.strip()
    
        return ''.join(xff.split()) if xff else remote_addr
    
    #限次后調用,還需等待多長時間才能再訪問
    def wait(self):
        """ Optionally, return a recommended number of seconds to wait before the next request. """
        return None  #返回的是等待的時間秒數
返回到 def check_throttles(self, request):

        throtttle_durations=[]
        
        for throttle in self.get_throttles():
            
            if not throttle.allow_request(request, self):
                #wait()的返回值就是要等待的多少秒,把秒數添加到數組里面
                self.throttled(request, throttle.wait())
           #數組就是要等待的秒時間
        if throttle_durations:
            #格式化,展示還需要等待多少秒
            durations = [
                duration for duration in throttle_durations
                if duration is not None
            ]
            duration = max(durations, default=None)
            self.throttled(request, duration)
分析def get_ident(self, request):pass
查看:
num_proxies = api_settings.NUM_PROXIES

到APISettings中ctrl+F查找NUM_PROXIES  
'NUM_PROXIES'=None

返回到def get_ident(self, request):pass函數方法
NUM_PROXIES如果為空走:
return ''.join(xff.split()) if xff else remote_addr
查看 SimpleRateThrottle類,繼承BaseThrottle,並沒有寫get_ident方法
但是寫了allow_request,和wait
class SimpleRateThrottle(BaseThrottle):
    """ A simple cache implementation, that only requires `.get_cache_key()` to be overridden. The rate (requests / seconds) is set by a `rate` attribute on the View class. The attribute is a string of the form 'number_of_requests/period'. Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') Previous request information used for throttling is stored in the cache. """
    cache = default_cache
    timer = time.time
    cache_format = 'throttle_%(scope)s_%(ident)s'
    scope = None
    THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
    
    def __init__(self):
        if not getattr(self, 'rate', None):
            self.rate = self.get_rate()
        self.num_requests, self.duration = self.parse_rate(self.rate)
    
    def get_cache_key(self, request, view):
        """ Should return a unique cache-key which can be used for throttling. Must be overridden. May return `None` if the request should not be throttled. """
        raise NotImplementedError('.get_cache_key() must be overridden')
    
    def get_rate(self):
        """ Determine the string representation of the allowed request rate. """
        if not getattr(self, 'scope', None):
            msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
                   self.__class__.__name__)
            raise ImproperlyConfigured(msg)
    
        try:
            return self.THROTTLE_RATES[self.scope]
        except KeyError:
            msg = "No default throttle rate set for '%s' scope" % self.scope
            raise ImproperlyConfigured(msg)
    
    def parse_rate(self, rate):
        """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """
        if rate is None:
            return (None, None)
        num, period = rate.split('/')
        num_requests = int(num)
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
        return (num_requests, duration)
    
    def allow_request(self, request, view):
        """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """
        if self.rate is None:
            return True
    
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
    
        self.history = self.cache.get(self.key, [])
        self.now = self.timer()
    
        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
    
    def throttle_success(self):
        """ Inserts the current request's timestamp along with the key into the cache. """
        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True
    
    def throttle_failure(self):
        """ Called when a request to the API has failed due to throttling. """
        return False
    
    def wait(self):
        """ Returns the recommended next request time in seconds. """
        if self.history:
            remaining_duration = self.duration - (self.now - self.history[-1])
        else:
            remaining_duration = self.duration
    
        available_requests = self.num_requests - len(self.history) + 1
        if available_requests <= 0:
            return None
    
        return remaining_duration / float(available_requests)
分析SimpleRateThrottle中的__init__方法
因為返回到get_throttles(self):  return[throttle() for throttle in self.throttle_classes]
throttle()對象加括號調用觸發__init__方法
#初始化沒有傳入參數,所以沒有'rate'參數
 def __init__(self):
        # 如果沒有rate就調用get_rate()進行賦值
        if not getattr(self, 'rate', None):
            self.rate = self.get_rate()
            #解析rate,用兩個變量存起來
        self.num_requests, self.duration = self.parse_rate(self.rate)

 所有繼承SimpleRateThrottle都會走__init__
返回到
 def check_throttles(self, request):

        throtttle_durations=[]
        #throttle初始化成功之后
        for throttle in self.get_throttles():
           #初始化成功之后調用allow_request方法,也就是SimpleRateThrottle中的allow_request
            if not throttle.allow_request(request, self):
               
                self.throttled(request, throttle.wait())
分析SimpleRateThrottle中的allow_request方法
  def allow_request(self, request, view):
        """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """
        #rate沒有值,就永遠也不會限制訪問
        if self.rate is None:
            return True
        #如果有值往下走
        #獲取緩存的key賦值給self.key
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
    
        self.history = self.cache.get(self.key, [])
        self.now = self.timer()
    
        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            #頻率失敗
            return self.throttle_failure()
        #頻率成功
        return self.throttle_success()
  #頻率失敗,返回false,沒有請求次數
    def throttle_failure(self):
        """ Called when a request to the API has failed due to throttling. """
        return False
    #頻率成功
    def throttle_success(self):
        """ Inserts the current request's timestamp along with the key into the cache. """
        # history中加時間,再成功再加,而且是加在insert列表的第一個,history長度就會越來越大,所以history的長度就是訪問了幾次
        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True
#一直成功一直成功,然后就超次了,所以就會返回False,所以就調用wait()
返回到
 def check_throttles(self, request):

        throtttle_durations=[]
        #throttle初始化成功之后
        for throttle in self.get_throttles():
           #初始化成功之后調用allow_request方法,也就是SimpleRateThrottle中的allow_request
            if not throttle.allow_request(request, self):
               
                self.throttled(request, throttle.wait())
找到drf資源文件throttling.py (有以下類)
以下是系統提供的三大頻率認證類,可以局部或者全局配置
ScopedRateThrottle(SimpleRateThrottle)
SimpleRateThrottle(BaseThrottle)
UserRateThrottle(SimpleRateThrottle)
分析UserRateThrottle(SimpleRateThrottle)
class UserRateThrottle(SimpleRateThrottle):
    """ Limits the rate of API calls that may be made by a given user. The user id will be used as a unique cache key if the user is authenticated. For anonymous requests, the IP address of the request will be used. """
    scope = 'user'
    
    #返回一個字符串
    def get_cache_key(self, request, view):
        #有用戶並且是認證用戶
        if request.user.is_authenticated:
            #獲取到用戶的id
            ident = request.user.pk
        else:
            ident = self.get_ident(request)
        #'throttle_%(user)s_%(request.user.pk)s'
        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }
點擊self.cache_format
cache_format = 'throttle_%(scope)s_%(ident)s'
    

   假設我的認證類采用了UserRateThrottle(SimpleRetaThrottle),
    for throttle in self.get_throttles():pass  產生的throttle的就是UserRateThrottle產生的對象,然后UserRateThrottle中沒有__init__,所以走SimpleRetaThrottle的__init__方法
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> getattr(self, <span class="hljs-string">'rate'</span>, <span class="hljs-keyword">None</span>):
        self.rate = self.get_rate()
    self.num_requests, self.duration = self.parse_rate(self.rate)


點擊self.get_rate(),
def get_rate(self):
"""
​ Determine the string representation of the allowed request rate.
​ """

#如果沒有scope直接拋異常,
#這里的self就是UserRateThrottle產生的對象,返回到UserRateThrottle獲取到 scope = 'user'
if not getattr(self, 'scope', None):
​ msg = ("You must set either .scope or .rate for '%s' throttle" %
​ self.class.name)
raise ImproperlyConfigured(msg)

    <span class="hljs-keyword">try</span>:
        <span class="hljs-comment">#self.THROTTLE_RATES['user'] ,這種格式就可以判斷THROTTLE_RATES是一個字典,點擊進入THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES   ,,跟之前一樣資源settings.py中ctrl+F查找DEFAULT_THROTTLE_RATES,</span>

# 'DEFAULT_THROTTLE_RATES': {
# 'user': None,
# 'anon': None,
# },
#然后在自己的settings.py中進行配置,就先走自己的配置,
#所以在這里的返回值是None
return self.THROTTLE_RATES[self.scope]
except KeyError:
# 當key沒有對應的value的時候就會報錯,而這里的user對應None所以是有value的
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)

返回到SimpleRetaThrottle

    def __init__(self):
        if not getattr(self, 'rate', None):
            #self.rate=None
            self.rate = self.get_rate()
        self.num_requests, self.duration = self.parse_rate(self.rate)
點擊 self.parse_rate(self.rate)

   def parse_rate(self, rate):
        """ Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds> """
        #如果rate是None,返回None,None
        if rate is None:
            return (None, None)
        #如果rate不是None,就得到的是字符串並且包含有一個‘/’,因為拆分后得到得是兩個結果,然后有int強轉,所以num一定是一個數字
        num, period = rate.split('/')
        num_requests = int(num)
        #period[0]取第一位,然后作為key到字典duration中查找,所以字母開頭一定要是s /m / h / d,發現value都是以秒來計算,所以得到rate得格式是'3/min' 也就是'3/60'
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
        return (num_requests, duration)


返回到SimpleRetaThrottle
    
    def __init__(self):
        if not getattr(self, 'rate', None):
            #self.rate=None
            self.rate = self.get_rate()
            #self.num_requests, self.duration =None,None
        self.num_requests, self.duration = self.parse_rate(self.rate)
為了能rate拿到值,就可以到自己得settings.py中配置
# drf配置
REST_FRAMEWORK = {
    # 頻率限制條件配置
    'DEFAULT_THROTTLE_RATES': {
        'user': '3/min',  
        'anon': None,
    },
}

返回
def get_rate(self):
     if not getattr(self, 'scope', None):
            msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
                   self.__class__.__name__)
            raise ImproperlyConfigured(msg)

        try:
            #return '3/min'
            return self.THROTTLE_RATES[self.scope]
        except KeyError:
            msg = "No default throttle rate set for '%s' scope" % self.scope
            raise ImproperlyConfigured(msg)


返回到SimpleRetaThrottle
    
    def __init__(self):
        if not getattr(self, 'rate', None):
            self.rate = self.get_rate()
            #self.num_requests:3, self.duration:60
        self.num_requests, self.duration = self.parse_rate(self.rate)

返回到
 def check_throttles(self, request):
    throtttle_durations=[]

    <span class="hljs-keyword">for</span> throttle <span class="hljs-keyword">in</span> self.get_throttles():
        <span class="hljs-comment"># 然后調用allow_request,到UserRateThrottle找,沒有走UserRateThrottle得父類SimpleRetaThrottle</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> throttle.allow_request(request, self):
           
            self.throttled(request, throttle.wait())

    
    def allow_request(self, request, view):
        """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """
        if self.rate is None:
            return True
        
        #rate有值rate = '3/60'
        # self.get_cache_key父級有這個方法,是拋異常,自己去實現這個方法
        #然后子級UserRateThrottle實現了這個方法
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
    
        self.history = self.cache.get(self.key, [])
        self.now = self.timer()
    
        # Drop any requests from the history which have now passed the
        # throttle duration
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()
UserRateThrottle中得get_cache_key方法
class UserRateThrottle(SimpleRateThrottle):
    """ Limits the rate of API calls that may be made by a given user. The user id will be used as a unique cache key if the user is authenticated. For anonymous requests, the IP address of the request will be used. """
    scope = 'user'
    
    def get_cache_key(self, request, view):
        if request.user.is_authenticated:
            ident = request.user.pk
        else:
            ident = self.get_ident(request)
        #'throttle_%(scope)s_%(ident)s' =》'throttle_user_1'
        return self.cache_format % {
            'scope': self.scope,
            'ident': ident
        }
    
    def allow_request(self, request, view):
        """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """
        if self.rate is None:
            return True
        
       #self.key = 'throttle_user_1'
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
        
        #django緩存
        #導包cache:from django.core.cache import cache as default_cache
        #緩存有過期時間,key,value,,,default是默認值
        #添加緩存:cache.set(key,defalut)
        #獲取緩存:cache.get(key,default) 沒有獲取到key采用默認值
        
        #獲取緩存key:'throttle_user_1'
        #初次訪問緩存為空列表,self.history=[],
        self.history = self.cache.get(self.key, [])
        #獲取當前時間存入到self.now
        self.now = self.timer()


​        
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()
        #history的長度與限制次數3進行比較
        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        #history的長度未達到限制次數3,代表可以訪問
        return self.throttle_success()
點擊self.throttle_success()
#將當前時間插入到history列表的開頭,將history列表作為數據存到緩存中,key是'throttle_user_1' ,過期時間60s
   def throttle_success(self):
        """ Inserts the current request's timestamp along with the key into the cache. """
        #將當前的時間插到第一位
        self.history.insert(0, self.now)
        #設置緩存,key:'throttle_user_1' history:[self.now, self.now...]
        # duration過期時間60s:'60'
        self.cache.set(self.key, self.history, self.duration)
        return True
 第二次訪問走到這個函數的時候

    def allow_request(self, request, view):
        """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """
        if self.rate is None:
            return True
        
       #self.key = 'throttle_user_1'
        self.key = self.get_cache_key(request, view)
        if self.key is None:
            return True
        
        #第二次訪問self.history已經有值,就是第一次訪問存放的時間
        self.history = self.cache.get(self.key, [])
        #獲取當前時間存入到self.now
        self.now = self.timer()
    
        #也就是當前的時間減去history緩存的時間(永遠都取第一次訪問的時間,所以是-1)是否大於過期時間
        #self.now - self.history[-1] >= self.duration
        #當超出的過期時間時,也就是第四次訪問
        while self.history and self.history[-1] <= self.now - self.duration:
            #pop是將最后的時間拿出來
            self.history.pop()
        #history的長度與限制次數3進行比較
        #history長度 第一次訪問為0, 第二次訪問為1,第三次訪問的時間長度為2,第四次訪問失敗
        if len(self.history) >= self.num_requests:
            #直接返回False,代表頻率限制了
            return self.throttle_failure()
        #history的長度未達到限制次數3,代表可以訪問
        return self.throttle_success()
def throttle_failure(self):
    return False
返回到
  def check_throttles(self, request):

        throtttle_durations=[]
      
        for throttle in self.get_throttles():
            #只要頻率限制了,allow_request 返回False,才會調用wait
            if not throttle.allow_request(request, self):
         
                self.throttled(request, throttle.wait())
調用的是SimpleRateThrottle的wait,因為UserRateThrouttle中沒有wait這個方法
    def wait(self):
        """ Returns the recommended next request time in seconds. """
        #如果緩存中還有history等30s
        if self.history:
            #self.duration=60, self.now當前時間-self.history[-1]第一次訪問時間
            remaining_duration = self.duration - (self.now - self.history[-1])
        else:
            #如果緩存中沒有,直接等60s
            remaining_duration = self.duration
        #self.num_requests=3,len(self.history)=3 結果3-3+1=1
        available_requests = self.num_requests - len(self.history) + 1
        if available_requests <= 0:
            return None
        # 30/1=30 返回的就是30s
        #如果意外第二次訪問就被限制了就是30/2=15s
        return remaining_duration / float(available_requests)

自定義頻率類

# 1) 自定義一個繼承 SimpleRateThrottle 類 的頻率類
# 2) 設置一個 scope 類屬性,屬性值為任意見名知意的字符串
# 3) 在settings配置文件中,配置drf的DEFAULT_THROTTLE_RATES,格式為 {scope字符串: '次數/時間'}
# 4) 在自定義頻率類中重寫 get_cache_key 方法
    # 限制的對象返回 與限制信息有關的字符串
    # 不限制的對象返回 None (只能放回None,不能是False或是''等)

短信接口 1/min 頻率限制

頻率:api/throttles.py
from rest_framework.throttling import SimpleRateThrottle

class SMSRateThrottle(SimpleRateThrottle):
scope = 'sms'

<span class="hljs-comment"># 只對提交手機號的get方法進行限制,因為get請求發送數據就是在params中傳送數據的,如果想要禁用post請發送過來的數據就要mobile = request.query_params.get('mobile') or request.data.get('mobile')</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_cache_key</span><span class="hljs-params">(self, request, view)</span>:</span>
    mobile = request.query_params.get(<span class="hljs-string">'mobile'</span>)
    <span class="hljs-comment"># 沒有手機號,就不做頻率限制</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> mobile:
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">None</span>
    <span class="hljs-comment"># 返回可以根據手機號動態變化,且不易重復的字符串,作為操作緩存的key</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">'throttle_%(scope)s_%(ident)s'</span> % {<span class="hljs-string">'scope'</span>: self.scope, <span class="hljs-string">'ident'</span>: mobile}</code></pre>
配置:settings.py
# drf配置
REST_FRAMEWORK = {
    # 頻率限制條件配置
    'DEFAULT_THROTTLE_RATES': {
        'sms': '3/min'  #60s內可以訪問三次請求
    },
}
視圖:views.py
from .throttles import SMSRateThrottle
class TestSMSAPIView(APIView):
    # 局部配置頻率認證
    throttle_classes = [SMSRateThrottle]
    def get(self, request, *args, **kwargs):
        return APIResponse(0, 'get 獲取驗證碼 OK')
    def post(self, request, *args, **kwargs):
        return APIResponse(0, 'post 獲取驗證碼 OK')
路由:api/url.py
url(r'^sms/$', views.TestSMSAPIView.as_view()),
限制的接口
# 只會對 /api/sms/?mobile=具體手機號 接口才會有頻率限制
# 1)對 /api/sms/ 或其他接口發送無限制
# 2)對數據包提交mobile的/api/sms/接口無限制
# 3)對不是mobile(如phone)字段提交的電話接口無限制
測試


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM