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:

self.check_permissions(request)
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, 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
self.perform_authentication(request)
#Permission component
self.check_permissions(request)
#Frequency components
self.check_throttles(request)

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

In app01.service.permissions.py:

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

At views.py:

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

Global view permissions

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}

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