首页 > 解决方案 > DRF 中的自定义未授权错误响应

问题描述

错误页面

如果任何请求未能验证此视图,用户将获得默认的 Django-Rest 页面。如果出现未经授权的请求,我如何自定义此响应。

@api_view(['GET'])
@authentication_classes([JWTTokenUserAuthentication])
@permission_classes([IsAuthenticated])
def home_view(request):
-----

标签: djangodjango-rest-frameworkdjango-viewsjwtdjango-rest-framework-simplejwt

解决方案


您可以创建一个自定义EXCEPTION_HANDLER函数

from rest_framework.views import exception_handler
from rest_framework.exceptions import NotAuthenticated
from rest_framework.response import Response


def custom_exception_handler(exc, context):
    if isinstance(exc, NotAuthenticated):
        return Response({"custom_key": "custom message"}, status=401)

    # else
    # default case
    return exception_handler(exc, context)

然后,在您的设置中将这个新的自定义功能连接起来,

REST_FRAMEWORK = {
    # other settings
    "EXCEPTION_HANDLER": "dotted.path.to.the.custom.function"

}

因此,您将得到如下结果,

在此处输入图像描述


推荐阅读