Django REST Framework - Separate permissions per methods

后端 未结 7 1942
栀梦
栀梦 2020-12-23 13:19

I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views.

Reading the documentation I se

7条回答
  •  失恋的感觉
    2020-12-23 14:10

    Permissions are applied to the entire View class, but you can take into account aspects of the request (like the method such as GET or POST) in your authorization decision.

    See the built-in IsAuthenticatedOrReadOnly as an example:

    SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
    
    class IsAuthenticatedOrReadOnly(BasePermission):
        """
        The request is authenticated as a user, or is a read-only request.
        """
    
        def has_permission(self, request, view):
            if (request.method in SAFE_METHODS or
                request.user and
                request.user.is_authenticated()):
                return True
            return False
    

提交回复
热议问题