rest-framework: rights component

A privilege Profile

Only the super-user can access the specified data, the average user can not access, so we'll have to limit the authority component

Two topical use

from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
    message = '不是超级用户,查看不了'
    def has_permission(self, request, view):
        # user_type = request.user.get_user_type_display()
        # if user_type == '超级用户':
        user_type = request.user.user_type
        print(user_type)
        if user_type == 1:
            return True
        else:
            return False
class Course(APIView):
    authentication_classes = [TokenAuth, ]
    permission_classes = [UserPermission,]

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')

Topical use only need to add in the view class:

permission_classes = [UserPermission,]

Three global use

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

Four source code analysis:

def check_permissions(self, request):
    for permission in self.get_permissions():
        if not permission.has_permission(request, self):
            self.permission_denied(
                request, message=getattr(permission, 'message', None)
                )

self.get_permissions()

def get_permissions(self):
     return [permission() for permission in self.permission_classes]

Permission to use class order: first class view of the permission class , then the settings in the configuration of permission classes , and finally with the default permissions class

Guess you like

Origin www.cnblogs.com/HUIWANG/p/11134584.html