首页 > 其他 > 详细

Django Rest Framework 频率组件

时间:2020-02-22 11:55:56      阅读:57      评论:0      收藏:0      [点我收藏+]

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

 

====(全局使用)

ratethrottle_classes.py

 

 

技术分享图片
#继承SimpleRateThrottle类
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
views.py

全局使用===》不用注册了

******************************************************************************************************************************************

 

 

Django Rest Framework 频率组件

原文:https://www.cnblogs.com/cou1d/p/12344475.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!