rest-framework之权限组件

一 权限简介

只用超级用户才能访问指定的数据,普通用户不能访问,所以就要有权限组件对其限制

二 局部使用

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')
View Code

局部使用只需要在视图类里加入:

permission_classes = [UserPermission,]

三 全局使用

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

四 源码分析

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)
                )
View Code

self.get_permissions()

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

权限类使用顺序:先用视图类中的权限类,再用settings里配置的权限类,最后用默认的权限类

 

posted @ 2018-10-10 14:59  刘清政  阅读(1623)  评论(0编辑  收藏  举报