1.  
  2. 主页
  3.  / 
  4. DRF实战教程
  5.  / 
  6. DRF实战之限制频率

DRF实战之限制频率

限制频率

开放平台的API接口调用需要限制其频率,以节约服务器资源和避免恶意的频繁调用。

内置频率类

在应用下新建一个mythrottle类。如下代码:

from rest_framework.throttling import SimpleRateThrottle


class VisitThrottle(SimpleRateThrottle):
    scope = "未认证用户"
  
    def get_cache_key(self, request, view):
        return  self.get_ident(request)
        
 
class UserThrottle(SimpleRateThrottle):
    scope = "已认证用户"
  
    def get_cache_key(self, request, view):
        return  request.user  

配置

对于未登录的用户根据IP来限制,对于已经登录的用户可以根据用户的唯一标识。

    'DEFAULT_THROTTLE_CLASSES': ['app06.mythrottle.UserThrottle', ],
    'DEFAULT_THROTTLE_RATES': {
        '未认证用户': '3/m',
        '已认证用户': '10/m',
    },
这篇文章对您有用吗? 1

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注