• drf频率组件


    drf频率组件

    限流Throttling

    可以对接口访问的频次进行限制,以减轻服务器压力。
    
    一般用于付费购买次数,投票等场景使用.
    

    使用

    # 可以在配置文件中,使用`DEFAULT_THROTTLE_CLASSES` 和 `DEFAULT_THROTTLE_RATES`进行全局配置
    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.AnonRateThrottle',
            'rest_framework.throttling.UserRateThrottle'
        ),
        'DEFAULT_THROTTLE_RATES': {
            'anon': '100/day',
            'user': '1000/day'  # DEFAULT_THROTTLE_RATES` 可以使用 `second`, `minute`, `hour` 或`day`来指明周期。
        }
    }
    
    # 局部配置  在具体视图中通过throttle_classess属性来配置
    from rest_framework.throttling import UserRateThrottle
    from rest_framework.views import APIView
    
    class ExampleView(APIView):
        throttle_classes = (UserRateThrottle,)
        ...
    
    

    可选限流类

    1) AnonRateThrottle
    
    限制所有匿名未认证用户,使用IP区分用户。
    
    使用`DEFAULT_THROTTLE_RATES['anon']` 来设置频次  # 在配置文件的字典中设置相应的值
    
    2)UserRateThrottle
    
    限制认证用户,使用User id 来区分。
    
    使用`DEFAULT_THROTTLE_RATES['user']` 来设置频次  # 在配置文件的字典中设置相应的值
    
    3)ScopedRateThrottle
    
    限制用户对于每个视图的访问频次,使用ip或user id。
    
    
    class ContactDetailView(APIView):
        throttle_scope = 'contacts'  # 设置在内存中的key
        ...
    
    class UploadView(APIView):
        throttle_scope = 'uploads'
        ...
    REST_FRAMEWORK = {
        'DEFAULT_THROTTLE_CLASSES': (
            'rest_framework.throttling.ScopedRateThrottle',
        ),
        'DEFAULT_THROTTLE_RATES': {
            'contacts': '1000/day',
            'uploads': '20/day'
        }
    }
    
    

    自定义限流类

    class TimeRateThrottle(SimpleRateThrottle):
        scope = 'time_rate'  # 一定要在settings配置DEFAULT_THROTTLE_RATES
        def get_cache_key(self, request, view):
            # return 'throttle_time_rate'
            if request.user and request.user.is_authenticated:  # 登陆用户
                return 'throttle_%s_%s' % (request.user.username, request.user.pk)
            # 必须写活 - 需要对游客非IP限制条件才需要自定义
            return 'throttle_time_rate'  # 游客,可以从request.META中取出IP等信息作为限制
    
  • 相关阅读:
    YUI: Effects Widgets
    提高Web页面的性能(一)
    textindent 隐藏文字时出现的 outline 问题
    通过 Dom 方法提高 innerHTML 性能
    IE8 beta1 中的 CSS 属性
    推荐的 CSS 书写顺序
    来自经典论坛的javascript小小考题
    IE5 到 IE8 的 CSS 兼容列表
    backgroundclip 与 backgroundorigin 的一则运用
    收集整理的对#!bin/sh的认识
  • 原文地址:https://www.cnblogs.com/zhouze/p/11385193.html
Copyright © 2020-2023  润新知