【问题标题】:DRF : Custom permission denied messageDRF:自定义权限被拒绝消息
【发布时间】:2021-09-17 12:18:52
【问题描述】:

如何将默认的 DRF-Permission Denied 消息
{"detail":"You do not have permission to perform this action."} 更改为类似的内容,
{"status": False, "message": "You do not have permission to perform this action."}

我找到了这个SO Answer,但是将Key 更改为message 并没有帮助

【问题讨论】:

    标签: django django-rest-framework django-permissions


    【解决方案1】:

    要在错误响应中包含状态,您可以编写自定义error handler

    from rest_framework.views import exception_handler
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
    
        if response.status_code == 403:
            response.data = {'status': False, 'message': response.data['detail']}
    
        return response
    

    在设置中:

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

    【讨论】:

      【解决方案2】:

      您可以通过扩展BasePermission 类来创建自定义权限,并使用带有自定义status_codedefault_detail 的自定义异常在该自定义权限中使用。

      class CustomForbidden(APIException):
          status_code = status.HTTP_403_FORBIDDEN
          default_detail = "custom error message"
      
      
      class CustomPermission(permissions.BasePermission):
          def has_permission(self, request, view):
              if not_allowed:
                  raise CustomForbidden
      

      【讨论】:

        猜你喜欢
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-15
        相关资源
        最近更新 更多