ajeet lakhani ajeet lakhani - 1 year ago 350
reST (reStructuredText) Question

Custom throttling response in django rest framework

I am using DRF for rest apis so now i am applying throttling to my apis. For that I created following throttle scopes




4)perViewsThrottles (varies with view)

currently i am getting

{"detail":"Request was throttled. Expected available in 32.0 seconds."}
as a response.

I want response something like this
{"message":"request limit exceeded","availableIn":"32.0 seconds","throttleType":"type"}

There is nothing in DRF docs for customisation. How can i customise my response according to requirement?

Answer Source

To do that, you can implement a custom exception handler function that returns the custom response in case of a Throttled exceptions.

from rest_framework.views import exception_handler
from rest_framework.exceptions import Throttled

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    if isinstance(exc, Throttled): # check that a Throttled exception is raised
        custom_response_data = { # prepare custom response data
            'message': 'request limit exceeded',
            'availableIn': '%d seconds'%exc.wait
        response.data = custom_response_data # set the custom response data on response object

  return response

Then, you need to add this custom exception handler to your DRF settings.

    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'

I think it would be slightly difficult to know the throttleType without changing some DRF code as DRF raises a Throttled exception in case of any the Throttle classes throttling a request. No information is passed to the Throttled exception about which throttle_class is raising that exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download