【发布时间】:2015-12-19 05:06:45
【问题描述】:
我正在使用 Django Rest Framework 3.2.3 (DRF) 和 Django Rest Framework JWT 1.7.2(DRF-JWT,https://github.com/GetBlimp/django-rest-framework-jwt)来创建登录令牌。
在发出 JWT 从 400 到 202 时,我需要更改无效凭据的状态代码(仅供参考:我的客户无法读取非 200 响应的正文)。我使用 Django Rest Framework 描述的自定义异常处理程序来实现它:http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
restapi/custom_exception.py
from rest_framework.views import exception_handler
from rest_framework import status
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)
print ('Exception raised: ' + str(response.status_code))
# Now add the HTTP status code to the response.
if response is not None:
if response.status_code != status.HTTP_403_FORBIDDEN:
response.status_code = status.HTTP_202_ACCEPTED
return response
在配置中:
'EXCEPTION_HANDLER': 'restapi.custom_exception.custom_exception_handler',
当使用无效凭据时,DRF-JWT 应该引发 ValidationError。在将无效凭据发布到 JWT 令牌认证接口时,我仍然收到 400 Bad Request 响应代码。
对于所有其他 DRF 接口,我都按预期获得了 202 状态代码。
如何让 DRF-JWT 为其 ValidationErrors 使用自定义异常处理程序?
【问题讨论】:
-
如果在视图中使用
raise ValidationError(msg),则执行自定义异常处理程序。如果在序列化程序中使用raise ValidationError(msg),则不使用自定义异常处理程序。有没有办法以某种方式扩展 DRF-JWT?
标签: python django django-rest-framework jwt