# Django Rest_Framework(六)限流Thro

2019-05-22  本文已影响0人  Gavininn

一、作用:

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

二、使用:

可以在配置文件中,使用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,)
上一篇 下一篇

猜你喜欢

热点阅读