zoukankan      html  css  js  c++  java
  • DRF之频率组件

    几种drf的频率组件使用总结

    一 

     - 定义一个频率类

    class RateThrottle():
        def allow_request(request, self):
            if 没有超过限制(伪代码):
                return True
            else:
                return False
        def wait(self): # 必写
            return 10

    - 指定频率类

    class BookView(APIView):
        throttle_classes = [RateThrottle]

    二  控制用户访问频率 (局部)

     - 导入

    from rest_framework.thortting import SimpleRateThrottle

     - 定义并继承simpleRateThrottle

    class RateThrottle(SimpleRateThrottle):
        # 指定访问频率
        rate = '5/m'
                        
        # 指定通过什么方式来区分用户
        def get_cache_key(self, request, view):
            return self.get_ident(request)

     - 同样要指定频率类

    class BookView(APIView):
        throttle_classes = [RateThrottle]

    三  控制用户访问频率(全局)

    - 继承类

    class RateThrottle(SimpleRateThrottle):
        # 指定访问频率
        scope = 'visit_rate'
                        
        # 指定通过什么方式来区分用户
        def get_cache_key(self, request, view):
            return self.get_ident(request)

    - 在settings里面指定频率类和访问频率

    - 在settings里面指定频率类和访问频率
                    REST_FRAMEWORK = {
                        "DEFAULT_THROTTLE_CLASSES": ('serializer.utils.app_throttles.RateThrottle',), # 路径
                        "DEFAULT_THROTTLE_RATES": {
                            "visit_rate": "5/m"  # 对应继承类
                        }
                    }
  • 相关阅读:
    Maven入门
    Windows Java安装
    cdh安装spark遇到的几个BUG
    SQL Server创建存储过程——动态SQL
    IDEA搭建scala开发环境开发spark应用程序
    liunx命令
    java常用 api
    缓存一致性问题
    git 命令
    nginx
  • 原文地址:https://www.cnblogs.com/lzmdbk/p/10103028.html
Copyright © 2011-2022 走看看