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等信息作为限制
原文地址:https://www.cnblogs.com/zhouze/p/11385193.html