要做到這一點,您可以使用執行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
正在引發該異常。