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

Customize Error Message When Permission Check Fails

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

默认情况下,当权限检查函数 return False.

时,会给出以下响应

HTTP 403 FORBIDDEN
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS

{ "detail": "You do not have permission to perform this action." }

我想更改上面的 "detail" 部分,提供对开发人员更友好的错误消息。我该怎么做才能确保每次权限检查失败时都显示消息?

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()

因此,subclass exceptions.PermissionDenied 并在您的自定义权限 class 中直接提升它似乎是完全合理的,例如

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

来自 Google 的任何人。现在有更简单的方法来提供自定义消息。只需将属性 message 添加到您的自定义权限 class。 Docs

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