• 265 第八篇:Django 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,]
    
    </span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> get(self, request):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> HttpResponse(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">get</span><span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(0, 0, 0, 1)">)
    
    </span><span style="color: rgba(0, 0, 255, 1)">def</span><span style="color: rgba(0, 0, 0, 1)"> post(self, request):
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> HttpResponse(<span style="color: rgba(128, 0, 0, 1)">'</span><span style="color: rgba(128, 0, 0, 1)">post</span><span style="color: rgba(128, 0, 0, 1)">'</span>)</pre>
    
    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里配置的权限类,最后用默认的权限类

  • 相关阅读:
    Linux下文件的压缩和解压
    Env: Linux下Source Insight安装
    [uart]2.tty和uart的函数调用流程
    [uart]stty命令使用
    腾讯云的云数据库MYSQL配置
    MySQL分支Percona
    MYSQL的历史
    MYSQL的价格
    mysql之event
    Linux下设置网卡静态ip
  • 原文地址:https://www.cnblogs.com/abdm-989/p/12168540.html
Copyright © 2020-2023  润新知