Django REST Framework限速

官方文档:http://www.django-rest-framework.org/api-guide/throttling/#throttling

settings.py配置

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

AnonRateThrottle:用户未登录请求限速,通过IP地址判断

UserRateThrottle:用户登陆后请求限速,通过token判断

DEFAULT_THROTTLE_RATES 包括 second, minute, hour, day

 

引用样例:

from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView

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

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

 

posted @ 2017-10-19 13:14  shhnwangjian  阅读(981)  评论(0编辑  收藏  举报