【问题标题】:How to catch PermissionDenied exception in Django REST Framework如何在 Django REST 框架中捕获 PermissionDenied 异常
【发布时间】:2020-09-10 09:34:09
【问题描述】:

如果特定的 DRF APIView 视图需要使用 permission_classes = [IsAuthenticated],当用户无法通过身份验证时,我如何捕获和处理 PermissionDenied 异常?

这是我现在的ExampleView

class ExampleView(APIView):

    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response(request.user)

到目前为止,如果用户无法通过身份验证,则此视图只会引发错误。发生该错误时如何捕获它并返回不同的内容?

【问题讨论】:

  • 可以分享一下render中的代码吗?
  • @KanishkAnand 我更新了问题
  • 你可以试试:value={{user:this.state.user}}
  • JSON 是一种文本格式,如 XML 或 CSV。一旦你在 JavaScript 中,你就是在处理 JavaScript 对象。
  • 看起来问题出在渲染中。你不能在那里打印整个对象,你需要一个原语(字符串、数字、布尔值等)

标签: python django authentication exception django-rest-framework


【解决方案1】:

为了改变响应的样式,您可以编写以下自定义异常处理程序:

from rest_framework.views import exception_handler

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)

    # Handle PermissionDenied
    if isinstance(exc, PermissionDenied):
        return custom_response()

    return response

然后,在您的settings.py 中,您需要配置 DRF 以使用此处理程序:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

更多信息在docs

【讨论】:

  • 感谢您指出这一点。但是,难道没有更直接的方法可以直接在视图中执行此操作吗?
  • 它发生在它到达视图之前
猜你喜欢
  • 2019-03-05
  • 2018-07-23
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2018-04-29
相关资源
最近更新 更多