节流器
- BaseThrottle
- allow_request
- 是否允许的请求的核心
- get_ident
- 获取客户端唯一标识
- wait
- allow_request
- SimpleRateThrottle
- get_cache_key
- 获取缓存标识
- get_rate
- 获取频率
- parse_rate
- 转换频率
- num/duration
- duration
- s
- m
- h
- d
- duration
- num/duration
- 转换频率
- allow_request
- 是否允许请求
- 重写的方法
- throttle_success
- 允许请求,进行请求记录
- throttle_failure
- 不允许请求
- wait
- 还有多少时间之后允许
- get_cache_key
- AnonRateThrottle
- get_cache_key
- 获取缓存key的原则
- get_cache_key
- UserRateThrottle
- 和上面一模一样
- ScopedRateThrottle
- 和上面一样
- 多写了从属性中获取频率
示例
在app目录下 我们新建一个文件 比如叫thottle.py
from django.contrib.auth.models import User
from rest_framework.throttling import SimpleRateThrottle
class MyThrottle(SimpleRateThrottle):
scope = "test"
# THROTTLE_RATES = {
# "test": "5/m"
# }
def get_cache_key(self, request, view):
if isinstance(request.user, User):
ident = request.auth
else:
ident = self.get_ident(request)
return self.cache_format % {
'scope': self.scope,
'ident': ident
}
那么在views.py的API中 我们就可以使用了
# 获取当前用户创建的书籍 要包括用户信息和他所有相关书籍的数据
class UserBookAPI(ListAPIView):
serializer_class = UserBookSerializer
queryset = User.objects.all()
authentication_classes = (LoginAuth, )
throttle_classes = (MyThrottle,)
def list(self, request, *args, **kwargs):
user = request.user
serializer = UserBookSerializer(user)
return Response(serializer.data)