频率组件的书写
例:书写频率组件:一分钟只能访问5次(CommonThrottle)
第一步:新建一个py文件(以throttling为例)
第二步:书写频率类,并继承继承SimpleRateThrottle
# 首先导入模块 from rest_framework.throttling import BaseThrottle, SimpleRateThrottle # 书写CommonThrottle类 class CommonThrottle(SimpleRateThrottle):
第三步:在类中书写频率限制代码
# 现在不继承BaseThrottle,如果继承它,写的代码太多 而要继承SimpleRateThrottle,帮咱省了很多代码 class CommonThrottle(SimpleRateThrottle): # scope = 'common' # 写一个类属性,随便命名--》去配置文件中配置 rate = '5/m' def get_cache_key(self, request, view): ip = request.META.get('REMOTE_ADDR') return ip # 返回什么,就以什么做频率限制(ip,用户id)
第四步:使用频率类
方式一:局部配置,在视图函数内书写:
class BookView(ViewSetMixin, ListCreateAPIView): throttle_classes = [CommonThrottle]
方式二:全局配置,在settings配置文件中书写
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ['app01.throttling.CommonThrottle'], }
局部禁用:
class 视图类(APIView): throttle_classes = []