Returning custom message when a permission is denied in DRF

前端 未结 7 1977
盖世英雄少女心
盖世英雄少女心 2021-02-13 01:20

Django REST Framework has an excellent piece of documentation about permissions. I\'ve been able to use pre-made permission classes and also built my own.

However, there

7条回答
  •  伪装坚强ぢ
    2021-02-13 01:58

    I faced the same problem using DRF 3.9.4. As a workaround I defined just a simple message property in the custom permission class and it works. You can also use getattr with the same result I guess.

    class IPWhitelistPermission(permissions.BasePermission):
    
        def __init__(self):
            super(IPWhitelistPermission, self).__init__()
            self._client_ip = None
    
        def has_permission(self, request, view):
            ip = get_client_ip(request)
            ret = IPWhitelist.is_whitelisted(ip)
    
            if not ret:
                logger = logging.getLogger('access')
                logger.warn("Unauthorized access from IP %s" % ip)
                self._client_ip = ip
            return ret
    
        @property
        def message(self):
            return "This IP is not whitelisted [{}]".format(self._client_ip)
    

提交回复
热议问题