权限检查失败时自定义错误消息

时间:2015-02-09 16:34:17

标签: python django django-rest-framework

DRF文档提供了how to create a custom permission的明确说明,提供了以下代码示例:

from rest_framework import permissions

class BlacklistPermission(permissions.BasePermission):
"""
Global permission check for blacklisted IPs.
"""

    def has_permission(self, request, view):
        ip_addr = request.META['REMOTE_ADDR']
        blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
        return not blacklisted

默认情况下,当权限检查函数返回False时,会给出以下响应。

  

HTTP 403 FORBIDDEN
  内容类型:application / json
  变化:接受
  允许:GET,POST,HEAD,OPTIONS

     

{       “detail”:“您无权执行此操作。”   }

我想更改上面的“详细信息”部分,提供更加开发人员友好的错误消息。我怎么能这样做,确保每次权限检查失败时都会显示消息?

2 个答案:

答案 0 :(得分:2)

Class APIView checks permissions via

def check_permissions(self, request):
    """
    Check if the request should be permitted.
    Raises an appropriate exception if the request is not permitted.
    """
    for permission in self.get_permissions():
        if not permission.has_permission(request, self):
            self.permission_denied(request)

here's permission_denied

def permission_denied(self, request):
    """
    If request is not permitted, determine what kind of exception to raise.
    """
    if not request.successful_authenticator:
        raise exceptions.NotAuthenticated()
    raise exceptions.PermissionDenied()

因此,将exceptions.PermissionDenied子类化并直接在自定义Permission类中提升它似乎是完全合理的,例如

class CustomForbidden(APIException):
    status_code = status.HTTP_403_FORBIDDEN
    default_detail = "Add your custom error message here"


class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if not_allowed:
            raise CustomForbidden

答案 1 :(得分:0)

适用于Google的所有人。现在有一种提供自定义消息的简便方法。只需将属性message添加到您的自定义权限类即可。 Docs

class CustomPermission(BasePermission):
    message = 'My custom message'