1.频率组件
在项目应用目录创建ratethrottle_classes.py文件,get_cache_key是必须存在的,它的返回值告诉当前频率控制组件要使用什么方式区分访问者(比如ip地址)
====(局部使用)
# 导入模块
from rest_framework.throttling import SimpleRateThrottle
# 定义频率类并继承SimpleRateThrottle
class RateThrottle(SimpleRateThrottle):
rate = '5/m' # 指定访问频率,5/m表示 每分钟5次
def get_cache_key(self, request, view):
return self.get_ident(request)
====(全局使用)
ratethrottle_classes.py
from rest_framework.throttling import SimpleRateThrottle
class RateThrottle(SimpleRateThrottle):
scope = "visit_rate"
def get_cache_key(self, request, view):
return self.get_ident(request)
settings.py
REST_FRAMEWORK = {
"DEFAULT_THROTTLE_CLASSES": ('ap.utils.throttles.RateThrottle',),
"DEFAULT_THROTTLE_RATES": {
"visit_rate": "5/m"
}
}
局部使用===》在views.py需要使用频率的 视图函数中注册频率类
from rest_framework.viewsets import ModelViewSet
from .authentication_classes import UserAuth
from .permission_classes import UserPerm
from .ratethrottle_classes import RateThrottle
class BookView(ModelViewSet):
# 在需要认证的数据接口里面指定认证类
authentication_classes = [UserAuth]
# 在需要权限的数据接口里面指定权限类
permission_classes = [UserPerm]
# 在需要频率的数据接口里面指定频率类
throttle_classes = [RateThrottle]
queryset = models.Book.objects.all()
serializer_class = BookSerizlizer
全局使用===》不用注册了
******************************************************************************************************************************************