从零开始的Linux运维屌丝之路,资源免费分享平台   运维人员首选:简单、易用、高效、安全、稳定、社区活跃的开源软件

Django rest 限流/频率控制

发布:蔺要红12-05分类: Python

# setting配置
# 自定义 和 使用 rest已经封装好的 二选一
# 一 自定义限频率
REST_FRAMEWORK = {
    # 使用自定义限流
    'DEFAULT_THROTTLE_CLASSES': ['utils.throttlings.UserThrottling', ],

    'DEFAULT_THROTTLE_RATES': {
        '未认证用户': '600/min',
        '已认证用户': '600/min',
    },
}
# utils.throttlings.UserThrottling
# SimpleRateThrottle 需要继承此类并且重写 get_cache_key
from rest_framework.throttling import SimpleRateThrottle


class VisitThrottling(SimpleRateThrottle):
    scope = '未认证用户'

    def get_cache_key(self, request, view):
        return self.get_ident(request)  # 拿ip当做key


class UserThrottling(SimpleRateThrottle):
    scope = '已认证用户'

    def get_cache_key(self, request, view):
        return request.user  # 当前登录的用户当做key

视图通用(自定义和rest封装好的都可以使用)
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle, ScopedRateThrottle # 导入rest封装好的类
from utils.throttlings import VisitThrottling # 导入自定义的频率限制类
# 导入的包都可以选择其中一种使用
class CartView(APIView):
    #  都是局部的
    # 节流 局部 空为不限制
    # throttle_classes = [VisitThrottling]
 
# 二 使用rest封装好的频率限制类  具体可以从 rest_framework.throttling 源码里看

# AnonRateThrottle
限制未认证的用户。通过传入请求的 IP 地址生成一个唯一的密钥来进行限制。
# UserRateThrottle
通过 API 将用户请求限制为给定的请求频率。用户标识用于生成一个唯一的密钥来加以限制。未经身份验证的请求将回退到使用传入请求的 IP 地址生成一个唯一的密钥来进行
# ScopedRateThrottle
可用于限制对 API 特定部分的访问。只有当正在访问的视图包含 .throttle_scope 属性时才会应用此限制。然后通过将请求的 “范围” 与唯一的用户标识或 IP 地址连接起来形成唯一的限流密钥


REST_FRAMEWORK = {
    # 使用 rest自带的分流  具体需要测试/ 选1-2个使用即可 UserRateThrottle ScopedRateThrottle AnonRateThrottle
    'DEFAULT_THROTTLE_CLASSES': ('rest_framework.throttling.UserRateThrottle',
                                 'rest_framework.throttling.ScopedRateThrottle',
                                 'rest_framework.throttling.AnonRateThrottle'),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '10/minute',
        'user': '10/minute',
        'throttle_scope': '11/minute',
    },
}

 
温馨提示如有转载或引用以上内容之必要,敬请将本文链接作为出处标注,如有侵权我会在24小时之内删除!

欢迎使用手机扫描访问本站