权限认证

简介

比如: 超级用户才可以访问指定的数据,普通用户访问不了. 所以使用权限组件对其限制

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

# models

class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    # user_type = models.IntegerField(choices=((1,'超级用户'),(2, '普通用户')))
    ty = models.Foreign(to='Type')
    
class Type(models.Model):
  	id = models.AutoField(primery_key=True)
    name = models.CharField(max_length=32)

局部使用

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

在视图类中加入

permission_classes = [UserPermission,]

全局使用

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

源码分析

原文地址:https://www.cnblogs.com/kp1995/p/10617243.html