美文网首页
# Django Rest_Framework(六)限流Thro

# Django Rest_Framework(六)限流Thro

作者: Gavininn | 来源:发表于2019-05-22 22:14 被阅读0次

一、作用:

可以对接口访问的频次进行限制,以减轻服务器的压力。一般用于付费购买次数,投票等场景使用。

二、使用:

可以在配置文件中,使用DEFAULT_THROTTLE_CLASSDEFAULT_THROTTLE_RATES进行全局配置。

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }
}

DEFAULT_THROTTLE_RATES 可以使用 second, minute, hourday来指明周期。

也可以在具体视图中通过throttle_classes属性来配置,如:

from rest_framework.throttling import UserRateThrottle
from rest_framework.view import APIView


class ExampleView(APIView):
        throttle_classes = (UserRateThrottle,)
        ...

三、可选限流类

1.AonRateThrottle

限制所有匿名未认证的用户。
使用DEFAULT_THROTTLE_RATES['anon'] 来设置频次

2.UserRateThrottle

限制认证用户,使用User id 来区分。
使用DEFAULT_THROTTLE_RATES['user'] 来设置频次

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'
    }
}

实例:

全局配置中设置访问频率
settings.py

 'DEFAULT_THROTTLE_RATES': {
        'anon': '3/minute',
        'user': '10/minute'
    }
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 StudentAPIView(RetrieveAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]
    throttle_classes = (UserRateThrottle,)

相关文章

网友评论

      本文标题:# Django Rest_Framework(六)限流Thro

      本文链接:https://www.haomeiwen.com/subject/jmbpzqtx.html