2015-02-09 66 views
2

的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
內容類型:應用程序/ JSON
各不相同:接受
允許:GET,POST,HEAD,OPTIONS

{ 「細節」:「您沒有權限執行此操作。「 }

我想更改上面的「詳細信息」部分,提供更易於開發人員的錯誤消息。我怎麼能這樣做,確保每次權限檢查失敗時都會顯示消息?

回答

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,並直接在您的自定義權限類提高它,例如

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