Django rest framework 03

Keywords: Python REST

Permission component

Source code

The source code execution process of the permission component is the same as that of the previous authentication component, as follows:

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):
                request, message=getattr(permission, 'message', None)

Thinking: if we want to do permission authentication, we first need to know who is currently logged in, so how do we know?
First, the three components in the rest framework are executed in order:

#Certified components
#Permission component
#Frequency components

There is such a code in the source code of the first executed authentication component

self.user, self.auth = user_auth_tuple

This user? Auth? Tuple happens to be the ancestor returned when we customize the authentication view

class TokenAuth(BaseAuthentication):
def authenticate(self, request):
return token_obj.user, token_obj.token #A tuple needs to be returned

So at this time, self. User = token Ou obj. User, self. Auth = token Ou obj. Token

Detail view permission


from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
    message = "SVIP Ability to visit" #Failure to pass validation returns an error
    def has_permission(self, request, view): #Fixed writing
        if request.user.user_type == 3:
            return True
        return False


class AuthorView(viewsets.ModelViewSet):
    authentication_classes = [TokenAuth,]
    permission_classes = [SVIPPermission,]
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

Global view permissions


Posted by areid on Wed, 04 Dec 2019 10:39:39 -0800