drf中的限制频率

drf中的限制频率是通过ip和用户id来进行限制的


使用方法

  1. 配置全局DEFAULT_THROTTLE_CLASSES
REST_FRAMEWORK = {

    'DEFAULT_THROTTLE_CLASSES': [
            'app06.mythrottle.VisitThrottle',
            'app06.mythrottle.UserThrottle',
                                 ],
    'DEFAULT_THROTTLE_RATES': {
         # s:表示秒  m:表示分钟  d:表示天   h:表示小时
        '未认证用户': '3/m',    # 和VisitThrottle里面的scope对应
        '认证用户': '10/m', 
    },
}
  1. 创建mythrottle文件
from rest_framework.throttling import SimpleRateThrottle

class VisitThrottle(SimpleRateThrottle):
    scope = '未认证用户'  # 在setting里面会用到
    def get_cache_key(self, request, view):
        print(self.get_ident(request))
        return self.get_ident(request)

class UserThrottle(SimpleRateThrottle):
    scope = '认证用户'   #会在setting里面用到
    def get_cache_key(self, request, view):
        print(request.user.id)
        return request.user  #返回用户的id
发布了32 篇原创文章 · 获赞 2 · 访问量 237

猜你喜欢

转载自blog.csdn.net/qq_33759361/article/details/104811808