权限组件

发布时间 2023-12-27 15:21:31作者: wellplayed

权限组件的书写

例:书写权限组件(CommonPermission)

第一步:新建一个py文件(以permission为例)

第二步:书写认证类,并继承继承BasePermission

# 首先导入模块
from rest_framework.permissions import BasePermission

# 书写权限类,重写has_permission方法
class CommonPermission(BasePermission):
    def has_permission(self, request, view):

 

第三步:在类中重写has_permission方法

# 只有超级管理员能访问,其他人都不能访问
class CommonPermission(BasePermission):
    def has_permission(self, request, view):
        # 到这,正常应该登录完了,登录完了 request.user 当前登录用户
        # 拿到用户后判断用户是否有权限--》用户表汇总用户类型字段 user_type--》根据类型判断权限
        try:
            # 后续可能使用ACL权限控制,RBAC权限控制
            user_type = request.user.user_type
            if user_type == 2:
                return True
            else:
                # user.get_字段名_display()  返回这个字段的choice对应的文字
                self.message = '您是:%s,您没有权限操作这个' % request.user.get_user_type_display()
                return False
        except Exception as e:
            # 未登录用户也没有权限
            if 'login' in request.path:
                return True
            else:
                self.message = '您没有登录,您没有权限操作这个'
                return False

 

第四步:使用权限类

方式一:局部配置,在视图函数内书写:

class BookDetailView(GenericViewSet):
        permission_classes = [CommonPermission]

 

方式二:全局配置,在settings配置文件中书写

REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': ['app01.permission.CommonPermission']
}

局部禁用:

class 视图类(APIView):
        permission_classes = []