加入收藏 | 设为首页 | 会员中心 | 我要投稿 武陵站长网 (https://www.50888.com.cn/)- 行业智能、建站、操作系统、语音技术、区块链!
当前位置: 首页 > 运营中心 > 网站设计 > 教程 > 正文

Restful 限流的使用方法

发布时间:2023-12-25 13:19:01 所属栏目:教程 来源:DaWei
导读: 当前,我们的 Restful Web API 不仅能够提供客户端需要的资源,还实现了认证和权限,可以保证数据的安全。那么我们搭建的 Restful Web API 能实现类似的功能吗?当然可以,这就涉及到了限流
当前,我们的 Restful Web API 不仅能够提供客户端需要的资源,还实现了认证和权限,可以保证数据的安全。那么我们搭建的 Restful Web API 能实现类似的功能吗?当然可以,这就涉及到了限流与过滤,接下来,我们就带领大家,一起实现这两个功能。

1.限流的使用方法
有时,为了防止恶意访问,或减轻服务器压力,我们需要对用户的访问频率进行限制。我们可在配置文件中,使用DEFAULT_THRottLE_CLASSES 和 DEFAULT_THRottLE_RATES进行全局配置,

REST_FRAMEWORK = {
    'DEFAULT_THRottLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THRottLE_RATES': {
        'anon': '100/day', # 匿名用户每天可访问100次
        'user': '1000/day' # 通过认证的用户每天可访问1000次
    }
}
DEFAULT_THRottLE_RATES 可以使用 second, minute, hour 或day来指明周期。也可以在具体视图中通过 throttle_classess 属性来配置,如

from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
class ExampleView(APIView):
    throttle_classes = (UserRateThrottle,)
    ...
    
2. Django Rest framework为我们提供的限流类
2.1 AnonRateThrottle
限制所有匿名未认证用户,不同用户的区分通过识别用户 IP 实现。使用DEFAULT_THRottLE_RATES['anon'] 来设置频率限制。

2.2 UserRateThrottle
限制认证用户,使用 User id 来区分不同用户。使用 DEFAULT_THRottLE_RATES['user'] 来设置频率限制。

2.3 ScopedrateThrottle
限制用户对于每个视图的访问频次,使用 ip 或 user id 区分不同用户。

例如:

class ContactListView(APIView):
    throttle_scope = 'contacts'
    ...
class ContactDetailView(APIView):
    throttle_scope = 'contacts'
    ...
class UploadView(APIView):
    throttle_scope = 'uploads'
    ...
REST_FRAMEWORK = {
    'DEFAULT_THRottLE_CLASSES': (
        'rest_framework.throttling.ScopedrateThrottle',
    ),
    'DEFAULT_THRottLE_RATES': {
        'contacts': '1000/day',
        'uploads': '20/day'
    }
}
3.实例
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import RetrieveAPIView
from rest_framework.throttling import UserRateThrottle
class StudentViewSet(ModelViewSet):
    queryset = StudentsModel.objects.all()
    serializer_class = StudentsSerializer
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]
    throttle_classes = (UserRateThrottle,)
 

(编辑:武陵站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章