【问题标题】:Custom unauthorized error response in DRFDRF 中的自定义未授权错误响应
【发布时间】:2021-07-27 22:21:57
【问题描述】:

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

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

【问题讨论】:

  • 具体来说,DRF custom exception handling
  • @JPG 我不确定这个问题是否值得被关闭。他在询问用于身份验证的自定义消息,这是非常具体的。您的链接没有提供答案(SO 参考的序列化程序,在 DRF 文档中创建自定义异常)。
  • @Guillaume 同意,JPG 的链接没有回答我的问题

标签: django django-rest-framework django-views jwt django-rest-framework-simplejwt


【解决方案1】:

您可以创建一个自定义EXCEPTION_HANDLER function 为,

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"

}

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

【讨论】:

  • 感谢您的回复。我已经实现了这一点并收到了客户的消息。有什么方法可以返回自定义 HTML 页面以进行未经授权的访问?
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 2021-03-31
  • 2019-05-06
  • 2019-01-16
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2021-09-03
相关资源
最近更新 更多