settings配置:
REST_FRAMEWORK={
# 限速
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle', # 没有登陆限速
'rest_framework.throttling.UserRateThrottle' # 登录限速
),
'DEFAULT_THROTTLE_RATES': {
'anon': '2/minute', #每分钟限制访问次数也可以使用每天 100/day
'user': '3/minute' #每分钟限制访问次数
}
}
在view中使用:
from rest_framework.throttling import UserRateThrottle,AnonRateThrottle\
class GoodsListViewSet(CacheResponseMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
#限速访问
throttle_classes = (UserRateThrottle,AnonRateThrottle)
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
filter_backends =(DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
filter_class = GoodsFilter