Django REST Framework 学习笔记(十三):频率组件

  • Title(EN): Django REST Framework Learning Notes (13): Throttle
  • Author: dog2

基本信息

  • 源码 rest_framework.throttling
  • 官方文档 API Guild - Throttling
  • 本文demo代码Github

源码分析

入口

rest_framework.views.APIViewdispath(self, request, *args, **kwargs)下手 ,dispath方法内 self.initial(request, *args, **kwargs) 进入三大认证 - 认证组件 self.perform_authentication(request) - 校验用户:游客、合法用户、非法用户 - 游客:代表校验通过,直接进入下一步校验(权限校验) - 合法用户:代表校验通过,将用户存储在request.user中,再进入下一步校验(权限校验) - 非法用户:代表校验失败,抛出异常,返回403权限异常结果 - 权限组件 self.check_permissions(request) - 校验用户权限:必须登录、所有用户、登录之后读写,游客只读、自定义用户角色 - 认证通过:可以进入下一步校验(频率认证) - 认证失败:抛出异常,返回403权限异常结果 - 频率组件 self.check_throttles(request) - 限制视图接口被访问的频率次数 - 限制的条件(IP、id、唯一键)、频率周期时间(s、m、h)、频率的次数(3/s) - 没有达到限次:正常访问接口 - 达到限次:限制时间内不能访问,限制时间达到后,可以重新访问

本文介权限组件。

views.APIView.initial()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)

# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg

# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme

# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request) #频率认证

views.APIView.check_throttles()

频率组件最重要的两个方法:allow_request()wait()

1
2
3
4
5
6
7
8
9
def check_throttles(self, request):  #频率组件核心代码
"""
Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
"""
throttle_durations = []
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
throttle_durations.append(throttle.wait())

views.APIView.get_throttles()

出现频率配置settings信息,经过查询源码的settings文件对频率配置为空

1
2
3
4
5
def get_throttles(self):
"""
Instantiates and returns the list of throttles that this view uses.
"""
return [throttle() for throttle in self.throttle_classes] #频率组件配置信息

throttling.SimpleRateThrottle

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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() #3.rate值就是方法get_rate的返回值(频率次数)
self.num_requests, self.duration = self.parse_rate(self.rate)

def get_cache_key(self, request, view):
raise NotImplementedError('.get_cache_key() must be overridden')

  #get_rate最后返回的结果是设置的频率次数
def get_rate(self):#1.在自定义类中要给scope属性赋值
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] #2.在settings文件中配置scope属性值对应的value
except KeyError:
msg = "No default throttle rate set for '%s' scope" % self.scope
raise ImproperlyConfigured(msg)

def parse_rate(self, rate):
if rate is None:
return (None, None)
num, period = rate.split('/') #4.rate有值,根据源码,自定义的rate值是一个字符串,而且是这种格式:'数字/以s,m,h,d之类开头的字母'
num_requests = int(num) #5.获得的数字就是设置的频率次数
duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] #6.获得是间隔的时间(以秒为单位)
return (num_requests, duration) #7.数据返回给__init__,解压赋值

def allow_request(self, request, view):
if self.rate is None:
return True
           #get_cache_key就是要重写的方法,若不重写,会直接抛出异常
self.key = self.get_cache_key(request, view) #8.自定义的时候需要重写的方法,有返回值,放入缓存中
if self.key is None:
return True

self.history = self.cache.get(self.key, []) #9.获取缓存,通过key取值
self.now = self.timer() #10.当前时间

# 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):
self.history.insert(0, self.now)
self.cache.set(self.key, self.history, self.duration)
return True

def throttle_failure(self):
return False

  #返回距下一次能请求的时间,限制的访问次数在parse_rate可以求出
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)

再看 views.APIView.check_throttles()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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频率限制

utils.throttles.py

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
# drf配置
REST_FRAMEWORK = {
# 频率限制条件配置
'DEFAULT_THROTTLE_RATES': {
'sms': '1/min'
},
}

views.py

1
2
3
4
5
6
7
8
9
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')

urls.py

1
2
3
4
5
6
7
from django.urls import path

from . import views

urlpatterns = [
path('sms/', views.TestSMSAPIView.as_view()),
]

Postman测试

  1. 只会对 /api/sms/?mobile=具体手机号 接口才会有频率限制,设置了限制频率,到达访问次数就会禁止
  2. /api/sms/ 或其他接口发送无限制
  3. 对数据包提交mobile的/api/sms/接口无限制
  4. 对不是mobile(如phone)字段提交的电话接口无限制