CBV模式下重写Message异常处理。
class OrderProcess(APIView):
# authentication_classes = [MyAuthentication, ]
# permission_classes = [MyPermissions, ]
# 执行自定义频率类
throttle_classes = [MyThrottling, ]
def get(self, request, *args, **kwargs):
result = {
"id" : 1,
"name" : "rest_framework"
}
json_str = json.dumps(result, ensure_ascii=False, indent=4)
return HttpResponse(json_str)
def throttled(self, request, wait):
"""
访问次数被限制时,定制错误信息
"""
class Throttled(exceptions.Throttled):
"""
继承父类Throttled,重写错误信息
"""
default_detail = '请求被限流.'
extra_detail_singular = '请 {wait} 秒之后再次访问.'
extra_detail_plural = '请 {wait} 秒之后再次访问.'
raise Throttled(wait)
FBV暂无,请参考全局重写方式
适合FBV模式下,CBV全局模式下,重写Message异常处理。
from rest_framework.exceptions import Throttled
from rest_framework.views import exception_handler
def customize_exception_handler(exc, context):
"""
自定义异常处理
:param exc:
:param context:
:return:
"""
response = exception_handler(exc, context)
if isinstance(exc, Throttled):
detail = {
'message': '请求被限流.',
'availableIn': '请 {wait} 秒之后再次访问.'.fromat(wait=exc.wait)
}
response.data = detail
return response
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'xxxxxx.customize_exception_handler'
}