要做到这一点,您可以使用执行custom exception handler function,如果发生Throttled
异常,将返回自定义响应。
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
然后,您需要将此自定义异常处理程序添加到您的DRF设置。
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
我认为这将是稍微很难知道throttleType
不改变一些DRF代码DRF在任何节气门类节流的请求的情况下,提出了一个Throttled
例外。没有任何信息传递给Throttled
例外,即哪个throttle_class
正在引发该异常。