Django rest Framework(DRF)源码解析——限流

三.限流
对于已经验证并且有权限的用户,我们还可以对其进行限流,反爬虫,加强安全性
DRF实现限流的原理是通过用户的IP或者用户名,把它加入列表,比如对只能访问一分钟内只能访问3次的资源。则每来一次把此IP访问时间放入列表之中进行记录。通过返回的数据是false还是true来看是否继续访问某个视图类。
 
3.1 check_throttles函数

"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""

检查请求是否应该被限流

 

此函数循环调用每一个限流类里的allow_request函数,把每一个没有通过的限流类里的外套()执行后的结果放在一个列表之中。等每一个限流类allow_request都执行完后。再遍历列表里面的值,把空值去除,通过max函数把最大值返回给用户,最后调throttled函数把对最大值进行返回

 

3.2 get_throttles函数

"""
Instantiates and returns the list of throttles that this view uses.
"""

 

类似于前面get_permissions函数,get_authenticators函数,返回一个限流类列表
 
3.3 allow_request函数

"""
Return `True` if the request should be allowed, `False` otherwise.
"""

 

类似于权限类里面的has_permission函数,返回true代表能够访问视图类
 
3.4 wait函数

"""
Optionally, return a recommended number of seconds to wait before
the next request.
"""

被拒绝访问后,提醒用户距离下一次访问还需要多久时间

 

3.5 throttled函数

"""
If request is throttled, determine what kind of exception to raise.
"""

 
 
 
 
3.6 系统限流类
3.6.1 BaseThrottle

"""
Rate throttling of requests.
"""

 
3.6.1.1 allow_request函数
此函数用于执行限流逻辑
BaseThrottle类里面的方法未写限流逻辑,用于继承重写的
 
3.6.1.2 get_ident函数
此函数用于获取标识,即IP或者是用户名
 
3.6.1.3 wait函数
 
 3.6.2 SimpleRateThrottle

"""
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.
"""

 
此类实现了通过用户的IP或者用户名来实现限流,继承自上面的BaseThrolttle类

3.6.21 get_cache_key函数

"""
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.
"""

此类必须被覆盖,用户获取唯一的用户标识符,如用户IP,或者用户名,request.user.username

Self.get_ident

3.6.22 scope = “xxxx”
如果使用这个类,这个类的scope属性必须得赋值,scope是代表此类使用哪个限流评率,比如在系统配置里面  ”DEFAULT_THROTTLE_RATES”: {“user”:”3/m”,”anonymoususer”:”3/h”}
Scope就是user或者anonymoususer
posted @ 2021-05-07 18:56  落秋巴  阅读(124)  评论(0编辑  收藏  举报