• Django Rest Framework 频率组件


    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

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

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

     

  • 相关阅读:
    每日一剂 14-6-6
    每日一剂 14-6-5
    每日一剂 14-6-4
    每日一剂 14-5-30
    Maven清理 .lastUpdated文件
    Docker 将项目做成镜像部署在docker中
    Docker 镜像拷贝到 正式环境运行
    Docker 安装 Tomcat
    Docker 安装 ActiveMq
    Docker 安装 nginx
  • 原文地址:https://www.cnblogs.com/cou1d/p/12344475.html
Copyright © 2020-2023  润新知