码迷,mamicode.com
首页 > 其他好文 > 详细

自定义频率认证

时间:2019-11-26 22:30:05      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:文件中   get   default   view   turn   use   使用   作用   lin   

- 自定义频率认证
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):
        ...

自定义频率认证

标签:文件中   get   default   view   turn   use   使用   作用   lin   

原文地址:https://www.cnblogs.com/xiongchao0823/p/11938769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!