自定义频率认证

- 自定义频率认证
from rest_framework.throttling import SimpleRateThrottle

"""
注意: 要继承 SimpleRateThrottle,不要继承 BaseThrottle
        因为BaseThrottle的wait和allow_request方法是没写的,
        而SimpleRateThrottle起到了一个中介的作用,写了这两个方法
        并且只需要重写get_cache_key方法
        allow_request: 配置一段时间内访问次数的方法
        wait: 达到次数后等待时间的方法
        get_ident: 在缓存中存取次数的方法
1. 继承BaseThrottle
2. 重写get_cache_key方法
3. 返回值必须是一个唯一的值,因为要通过唯一的值入django默认的缓存中存取token在一定时间中的请求次数
"""


class PersonalBaseThrottle(SimpleRateThrottle):
    - 根据这个去settings.py文件中配置的频率认证取值
    scope = 'three'
    - 如果设置了rate就直接去使用rate的配置的频率了, 就不去settings.py去找了

    def get_cache_key(self, request, view):
        print(request.user.id)
        - 要不返回空, 要不就返回一个唯一的可以从缓存中取值的东西
        return request.user.id

REST_FRAMEWORK = {
    - 频率认证模块
    'DEFAULT_THROTTLE_RATES': {
            'three': '3/min',
        },
}
views.py 设置

class xxx(xxx):
    throttle_classes = [PersonalBaseThrottle]
    def xxx(xx):
        ...
posted @ 2019-11-26 22:00  cheerxiong  阅读(167)  评论(0编辑  收藏  举报