I was trying to implement throttling following the django rest framework guide. Since I don't need to create another throttle class, I tried to use the .throttle_scope attribute. So, I implemented it like this:
class MyView(APIView):
throttle_scope = 'my_scope'
def post(self, request) -> Response:
# do something
return Response(status=status.HTTP_200_OK)
And in the settings I wrote something like this:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES': {
'my_scope': '1/minute',
}
}
I tried, using postman, to make more than 1 request per minute to that endpoint and I never received a 429 code. Than I tried creating a new throttle class and using the .throttle_classes attribute, like this:
class MyView(APIView):
throttle_classes = [MyThrottle]
def post(self, request) -> Response:
# do something
return Response(status=status.HTTP_200_OK)
class MyThrottle(UserRateThrottle):
scope = 'my_scope'
I left the settings unchanged and it worked as expected.
So now I'm wondering, could it be that the throttling_scope attribute only works if the user is anonymous?
I'm doing this assumption because I tried to make MyThrottle to inherit from AnonRateThrottle
instead of UserRateThrottle
and it didn't work. By the way, all the users who have access to this endpoint are all authenticated, thus I thought that ScopedRateThrottle
is more like AnonRateThrottle
.
The problem was trivial, and I solved it by adding ScopedRateThrottle
inside:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
...
'rest_framework.throttling.ScopedRateThrottle'
],
...
}
I tested again and the problem was solved.