REST-framework快速构建API--权限

我们在访问资源时,有些资源保密程度较高,需要特殊的人员才能访问。比如,获取公司的每日收入流水的API接口,只能CEO才能查看。 

这时,我们就需要将资源设定权限了。

REST-framework实现如下:

一、权限级别定义

我们规定用户类型为三种:

  • 普通用户
  • 管理员
  • 超级管理员
class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    type_choices = ((1, "普通用户"), (2, "管理员"), (3, "超级管理员"))
    user_type = models.IntegerField(choices=type_choices, default=1)

  其中,超级管理员可以查看公司每日收入流水。

二、权限控制

from rest_framework.permissions import BasePermission
class SVIPPermission(BasePermission):
    message="超级管理员才能访问!"
    def has_permission(self, request, view):
        user = User.objects.filter(name=request.user).first()
        if user.user_type==3:
            return True
        return False

  

三、权限应用

局部应用

class BookModelView(viewsets.ModelViewSet):
    authentication_classes = [TokenAuth,]
    permission_classes = [SVIPPermission,]
    queryset = Book.objects.all()
    serializer_class = BookModelSerializers

  

人员权限:

 人员对应的token:

扫描二维码关注公众号,回复: 5239555 查看本文章

访问测试如下:

普通用户访问Books资源:

超级管理员访问资源:

全局应用

REST_FRAMEWORK={
    "DEFAULT_AUTHENTICATION_CLASSES":["app01.utils.TokenAuth",],
    "DEFAULT_PERMISSION_CLASSES": ["app01.utils.SVIPPermission", ]

}

  

猜你喜欢

转载自www.cnblogs.com/skyflask/p/10404424.html