restframework的权限

 

  权限的主要应用比如指定的数据,vip用户或者付费才能观看的,普通用户不能访问,我们就可以用权限组件对其进行限制

# 权限的都是发生在认证后面的,所以认证时要返回obj.user,权限判断的时候好直接获取用户

from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
    message = '不是vip用户,查看不了'
  # 定义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')

和认证组件的使用差不多,通常我们会自定义py文件来单独写,作为模块导入使用

也有局部使用和全局使用

# 局部使用
    permission_classes = [UserPermission,]

# 全局使用
    REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
    "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
}
原文地址:https://www.cnblogs.com/tuzaizi/p/13486846.html