25
loading...
This website collects cookies to deliver better user experience
Throttling is similar to permissions, in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API
exceptions.Throttled
exception will be raised, and the main body of the view will not run.DEFAULT_THROTTLE_CLASSES
and DEFAULT_THROTTLE_RATES
settings.REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '20/day',
'user': '50/day'
}
}
DEFAULT_THROTTLE_RATES
may include second
, minute
, hour
, or day
as the throttle period.Unauthenticated users will be able to only make 20 requests per day to our API, the IP address of the incoming request is used to generate a unique key to throttle against.
Authenticated users will be able to make 50 requests per day to our API, for these the id of the user is going to be used to generate the unique key.
throttle_classes
attribute on the APIView
class-based views.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)
ExampleView
will use the UserRateThrottle
class to limit the number of requests that this view can receive, the rates, in this case, are still defined on the DEFAULT_THROTTLE_CLASSES
settings key.UserRateThrottle
class and specifying a new rate.from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
class CustomUserRateThrottle(UserRateThrottle):
rate= '5/day'
class VeryLimitedView(APIView):
throttle_classes = [CustomUserRateThrottle]
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
ScopedRateThrottle
class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a .throttle_scope
attribute.DEFAULT_THROTTLE_RATES
setting using a key from the request "scope".class ContactListView(APIView):
throttle_scope = 'contacts'
...
class ContactDetailView(APIView):
throttle_scope = 'contacts'
...
class UploadView(APIView):
throttle_scope = 'uploads'
...
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.ScopedRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'contacts': '100/day',
'uploads': '50/day'
}
}
ContactListView
or ContactDetailView
would be restricted to a total of 100 requests per day. User requests to UploadView
would be restricted to 50 requests per day.BaseThrottle
class which you can override to create custom throttles with custom implementations.