Throttling
Throttling is similar to permissions, in that it determines if a request should be authorized. Throttling indicates a temporary state, and is used to control the rate of requests that clients can make to an API.
Setting the Throttling Policy
The default throttling policy may be set globally using the DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES settings.
python
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
}Rate descriptions used in DEFAULT_THROTTLE_RATES may include second, minute, hour, or day as the throttle period.
You can also set the throttling policy on a per-view or per-viewset basis.
Class-Based Views
python
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)Function-Based Views
python
from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle
from rest_framework.response import Response
@api_view(['GET'])
@throttle_classes([UserRateThrottle])
def example_view(request):
return Response({'status': 'request was permitted'})Built-in Throttles
AnonRateThrottle: Throttles unauthenticated users based on their IP address. Useful for preventing scraping or brute force attacks.UserRateThrottle: Throttles authenticated users based on their user ID.ScopedRateThrottle: Allows you to throttle specific parts of the API independently. This is done by adding a.throttle_scopeattribute on the view.
python
class ContactListView(APIView):
throttle_classes = [ScopedRateThrottle]
throttle_scope = 'contacts'
# ...
class UploadView(APIView):
throttle_classes = [ScopedRateThrottle]
throttle_scope = 'uploads'
# ...Then configure the rates for those scopes in settings:
python
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.ScopedRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'
}
}