drf三大组件之频率认证组件

复习

"""
1、认证组件:校验认证字符串,得到request.user
    没有认证字符串,直接放回None,游客
    有认证字符串,但认证失败抛异常,非法用户
    有认证字符串,且认证通过返回 用户,认证信息 元组,合法用户
        用户存放到request.user | 认证信息存放到request.auth
        
    自定义认证类
    class MyAuthentication(BaseAuthentication):
        def authenticate(self, request):
            # 1)从request中拿auth字符串:return None | 继续
            # 2)校验auth:抛异常 | (user, auth)
            
    全局或局部配置
    REST_FRAMEWORK = {
        # 认证类配置
        'DEFAULT_AUTHENTICATION_CLASSES': [
            '自定义的认证类MyAuthentication',
        ],
    }
    class MyAPIView(APIView):
        authentication_calsses = []
        pass
    
    
2、权限组件:校验request.user是否拥有权限
    有权限,返回True
    无权限,返回False
    
    自定义权限类:
    class MyPermission(BasePermission):
        def has_permission(self, request, view):
            # 1)request.user或其他信息(请求方式)等判断:True | False
            
    全局或局部配置
    REST_FRAMEWORK = {
        # 权限类配置
        'DEFAULT_PERMISSION_CLASSES': [
            '自定义的权限类MyPermission',
        ],
    }
    class MyAPIView(APIView):
        permission_classes = []
        pass
"""

频率类源码

入口
# 1)APIView的dispath方法中的 self.initial(request, *args, **kwargs) 点进去
# 2)self.check_throttles(request) 进行频率认证

# 频率组件核心源码分析
def check_throttles(self, request):
    throttle_durations = []
    # 1)遍历配置的频率认证类,初始化得到一个个频率认证类对象(会调用频率认证类的 __init__() 方法)
    # 2)频率认证类对象调用 allow_request 方法,判断是否限次(没有限次可访问,限次不可访问)
    # 3)频率认证类对象在限次后,调用 wait 方法,获取还需等待多长时间可以进行下一次访问
    # 注:频率认证类都是继承 SimpleRateThrottle 类
    for throttle in self.get_throttles():
        if not throttle.allow_request(request, self):
            # 只要频率限制了,allow_request 返回False了,才会调用wait
            throttle_durations.append(throttle.wait())

            if throttle_durations:
                # Filter out `None` values which may happen in case of config / rate
                # changes, see #1438
                durations = [
                    duration for duration in throttle_durations
                    if duration is not None
                ]

                duration = max(durations, default=None)
                self.throttled(request, duration)

自定义频率类

# 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'

    # 只对提交手机号的get方法进行限制
    def get_cache_key(self, request, view):
        mobile = request.query_params.get('mobile')
        # 没有手机号,就不做频率限制
        if not mobile:
            return None
        # 返回可以根据手机号动态变化,且不易重复的字符串,作为操作缓存的key
        return 'throttle_%(scope)s_%(ident)s' % {'scope': self.scope, 'ident': mobile}
配置:settings.py
# drf配置
REST_FRAMEWORK = {
    # 频率限制条件配置
    'DEFAULT_THROTTLE_RATES': {
        'sms': '1/min'
    },
}
视图: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)字段提交的电话接口无限制

猜你喜欢

转载自www.cnblogs.com/DcentMan/p/11722340.html