1. api/throttle.py
# -*- coding: utf8 -*-
from rest_framework.throttling import SimpleRateThrottle
class AnonymousThrottle(SimpleRateThrottle):
scope = 'anonymous'
def get_cache_key(self, request, view):
print(self.get_ident(request))
return self.get_ident(request)
class StudentThrottle(SimpleRateThrottle):
scope = 'student'
def get_cache_key(self, request, view):
print(request.user.name)
return request.user.name
2. settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['api.authenticate.StudentAuthenticate'],
'DEFAULT_PERMISSOIN_CLASSES': ['api.permission.GradeOnePermisson'],
'UNAUTHENTICATED_USER': None, # request.user
'UNAUTHENTICATED_TOKEN': None, # request.auth
'DEFAULT_THROTTLE_CLASSES': ['api.throttle.StudentThrottle', 'api.throttle.AnonymousThrottle'],
'DEFAULT_THROTTLE_RATES': {
'anonymous': '2/m',
'student': '5/m',
}
}
3. api/views.py
class TokenView(GenericViewSet):
# authentication_classes = []
# permission_classes = [GradeOnePermission]
parser_classes = [JSONParser, ]
# throttle_classes = []
def get(self, request, *args, **kwargs):
name = request.query_params.get('name')
try:
stu = Student.objects.get(name=name)
except Student.DoesNotExist:
raise ParseError(_('Student does not include this name'))
token = stu.token.token
res = dict()
res['code'] = 200
res['name'] = name
res['token'] = token
logger.info(pformat(res))
return Response(data=res, status=status.HTTP_200_OK)
4. postman
(1) http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86
(2)http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86
(3)http://127.0.0.1:8011/api/v1/token/?name=student1&token=dbfa6b230b9ca22302a00ea918346f86
return:
{
"detail": "Request was throttled. Expected available in 55 seconds."
}