Django之DRF源码分析(四)---频率认证组件
核心源码
    def check_throttles(self, request):
        """
        Check if request should be throttled.
        Raises an appropriate exception if the request is throttled.
        """
        for throttle in self.get_throttles():
            if not throttle.allow_request(request, self):
                self.throttled(request, throttle.wait())
class SimpleRateThrottle(BaseThrottle):
    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):
        # 这里需要我们在定义 频率类的时候 重写该方法,返回的是访问者的ip,并放在缓存中
        """
        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.
        确认允许请求的频率的字符串表达形式
        """
        # 去继承SimpleRateThrottle的类的对象中 反射 scope ,如果存在,则不执行,如果不存在执行if
        if not getattr(self, 'scope', None):
            msg = ("You must set either `.scope` or `.rate` for '%s' throttle" %
                   self.__class__.__name__)
            raise ImproperlyConfigured(msg)
        try:
            # 根据我配置的scope 去 settings.py 中的 REST_FRAMEWORK 中去获取DEFAULT_THROTTLE_RATES 中的值  这里我配置的是 "qzk":"3/m"
            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
        num, period = rate.split('/')
        # 将num 转成数字类型的整型
        num_requests = int(num)
        # 此时 period = 字符串 “m” 或 “minute”
        # duration 是在 下面的 字典中的映射关系中取第{...}["m"]
        # period[0] 表示 在字符串中取第一个字符(索引0)
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
        # 此时返回的 num_reuqets=3   duration=60
        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`.
        验证通过 调用 throttle_success
        On failure calls `throttle_failure`.
        验证失败 调用 `throttle_failure`
        """
        if self.rate is None:
            return True
		# 这里的self.key 获取的值是  访问者的 ip(存在缓存中),我们在自己写的频率类中重写了该方法,这个方法返回时很么我们就以什么做过滤的 key
        self.key = self.get_cache_key(request, view)
        # 如果获取不到ip 则返回none
        if self.key is None:
            return True
		# 根据ip 获取 self.cache缓存中的 value---> [ctime2,ctime1]
        self.history = self.cache.get(self.key, [])  # self.history 就是当前访客的访问时间列表
        # 获取当前时间
        self.now = self.timer()
        # Drop any requests from the history which have now passed the
        # throttle duration
        # 如果 当前访客的时间列表不为空(有值) 并且 最后一个值 <= 当前时间-你设定的时间范围(60)
        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()  # 将时间列表中的最后一个pop弹栈出去(删除)
        if len(self.history) >= self.num_requests:  # 如果列表的长度 >= 你设置的次数(3)
            return self.throttle_failure()   # 返回 False
        return self.throttle_success()  # 返回True
    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)
BaseThrottle 类
class BaseThrottle(object):
    """
    Rate throttling of requests.
    """
    def allow_request(self, request, view):
        """
        Return `True` if the request should be allowed, `False` otherwise.
        """
        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')
        # 获取 ip地址
        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
"""频率部分源码执行流程"""
'''
	先写一个频率校验的类(继承SimpleRateThrottle) ---> 在该类中 配置 scope参数---> 重写 get_cache_key 方法 并返回self.get_ident(request)---->在需要校验的类中配置 该校验类
	执行步骤:
		1.APIView
		2.---->dispatch
		3.---->self.initial(request, *args, **kwargs)
		4.---->self.check_throttles(request)
		5.---->throttle.allow_request(request, self)
		6.---->self.get_cache_key(request, view)(自己重写的)(返回的是ip)
		7.---->self.cache.get(self.key, []) 根据ip获取当前ip的 时间列表
		8.---->需要用到参数(self.rate,self.num_requests,self.duration)在类实例化的时已经执行了如下代码(__init__):
				8.1--> self.rate = self.get_rate()-->self.THROTTLE_RATES[self.scope]
					-->api_settings.DEFAULT_THROTTLE_RATES(配置文件中找)
					这里 self.rate  ---> 是前面配置的 'qzk':'3/m'
				8.2-->self.num_requests, self.duration = self.parse_rate(self.rate)
					这里 self.num_requests 是设定的访问限制次数(3)
						self.duration  是访问的时间限制(60)
		9.----> 通过如上数据,并进行一通逻辑判断, 返回
        		True:——> 执行throttle_success:
        					self.history.insert(0, self.now)  # 把当前访问时间添加到时间列表
        					# 再将 key,history,duration 在 {} 中更新
        					self.cache.set(self.key, self.history, self.duration)
                False :--->  执行throttle_failure ,返回 Ture
'''
Django之DRF源码分析(四)---频率认证组件的更多相关文章
- Django之DRF源码分析(二)---数据校验部分
		Django之DRF源码分析(二)---数据校验部分 is_valid() 源码 def is_valid(self, raise_exception=False): assert not hasat ... 
- Django与drf 源码视图解析
		0902自我总结 Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View """ 1)as_view()是入口,得到view函数地址 2) ... 
- 使用react全家桶制作博客后台管理系统  网站PWA升级  移动端常见问题处理  循序渐进学.Net Core Web Api开发系列【4】:前端访问WebApi  [Abp 源码分析]四、模块配置  [Abp 源码分析]三、依赖注入
		使用react全家桶制作博客后台管理系统 前面的话 笔者在做一个完整的博客上线项目,包括前台.后台.后端接口和服务器配置.本文将详细介绍使用react全家桶制作的博客后台管理系统 概述 该项目是基 ... 
- Django搭建及源码分析(三)---+uWSGI+nginx
		每个框架或者应用都是为了解决某些问题才出现旦生的,没有一个事物是可以解决所有问题的.如果觉得某个框架或者应用使用很不方便,那么很有可能就是你没有将其使用到正确的地方,没有按开发者的设计初衷来使用它,当 ... 
- Django如何启动源码分析
		Django如何启动源码分析 启动 我们启动Django是通过python manage.py runsever的命令 解决 这句话就是执行manage.py文件,并在命令行发送一个runsever字 ... 
- ASP.NET Core[源码分析篇] - Authentication认证
		原文:ASP.NET Core[源码分析篇] - Authentication认证 追本溯源,从使用开始 首先看一下我们通常是如何使用微软自带的认证,一般在Startup里面配置我们所需的依赖认证服务 ... 
- external-provisioner源码分析(3)-组件启动参数分析
		更多ceph-csi其他源码分析,请查看下面这篇博文:kubernetes ceph-csi分析目录导航 external-provisioner源码分析(3)-组件启动参数分析 本文将对extern ... 
- ceph-csi组件源码分析(1)-组件介绍与部署yaml分析
		更多ceph-csi其他源码分析,请查看下面这篇博文:kubernetes ceph-csi分析目录导航 ceph-csi组件源码分析(1)-组件介绍与部署yaml分析 基于tag v3.0.0 ht ... 
- ceph-csi源码分析(2)-组件启动参数分析
		更多ceph-csi其他源码分析,请查看下面这篇博文:kubernetes ceph-csi分析目录导航 ceph-csi源码分析(2)-组件启动参数分析 ceph-csi组件的源码分析分为五部分: ... 
随机推荐
- Python中的next()\iter()函数详解
			什么是可迭代的对象(Iterable,即可以用for循环的对象)和迭代器(Iterator) Iterable: 一类是:list.tuple.dict.set.str 二类是:generator(都 ... 
- 接口自动化框架2-升级版(Pytest+request+Allure)
			前言: 接口自动化是指模拟程序接口层面的自动化,由于接口不易变更,维护成本更小,所以深受各大公司的喜爱. 第一版入口:接口自动化框架(Pytest+request+Allure) 本次版本做了一些升级 ... 
- Certification information不能过大
			/* If certification information is too big this event can't be transmitted as it would cause failure ... 
- Sc config http start= disabled
			我不小心使用这个命令 Sc config http start= disabled, 现在http服务 无法启动 管理员运行 sc config http start= demand & ne ... 
- 深入解密来自未来的缓存-Caffeine
			1.前言 读这篇文章之前希望你能好好的阅读: 你应该知道的缓存进化史 和 如何优雅的设计和使用缓存? .这两篇文章主要从一些实战上面去介绍如何去使用缓存.在这两篇文章中我都比较推荐Caffeine这款 ... 
- 关于 Object.defineProperty()
			通常,定义或者修改一个JS对象,有以下方式: // 1. 字面量 let obj = { name: 'cedric', age: 18 } // 2. new Object() let obj = ... 
- Maven 教程(20)— 使用maven-assembly-plugin插件来定制化打包
			原文地址:https://blog.csdn.net/liupeifeng3514/article/details/79777976 简单的说,maven-assembly-plugin 就是用来帮助 ... 
- Python【每日一问】21
			问: [基础题]输入某年某月某日,判断这一天是这一年的第几天? [提高题]用 *号输出字母 C的图案 答: [基础题]输入某年某月某日,判断这一天是这一年的第几天? 方法1: import time ... 
- day58——模板继承、组件、自定义标签和过滤器、inclusion_tag、静态文件配置、url别名和反向解析、url命名空间
			day58 模板相关 模板继承(母版继承) 1. 创建一个xx.html页面(作为母版,其他页面来继承它使用) 2. 在母版中定义block块(可以定义多个,整个页面任意位置) {% block co ... 
- 通过ip查询相关网络位置信息
			结果: 
