zoukankan      html  css  js  c++  java
  • drf--权限组件

    权限简介

    权限就是某些功能只对特定的用户开放,比如django中创建用户可分为超级用户和普通用户,此时超级用户就有权限进入后台管理系统,而普通用户就没有权限,这是怎么做到的呢?

    这就是权限组件的作用。

    局部使用

    from rest_framework.permissions import BasePermission
    
    class UserPermission(BasePermission):
        """自定义权限类:继承BasePermission,重写has_permission方法"""
        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,]
    

    全局使用

    # 在settings.py中进行设置
    
    REST_FRAMEWORK={
        "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",],
        "DEFAULT_PERMISSION_CLASSES":["app01.service.permissions.SVIPPermission",]
    }
    

    源码分析

    # permission.py
    
    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)
                    )
    
    # self.get_permissions()
    
    def get_permissions(self):
         return [permission() for permission in self.permission_classes]
    

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

  • 相关阅读:
    深入理解jsonp跨域请求原理
    vue项目性能优化总结
    脱离Office约束,C#结合Mpxj组件完美解析MSProject(.mpp)文件
    将list转换成DataTable
    json时间格式化
    C# DES加密解密
    asp.net mvc ViewBag常用操作
    Jquery ajax与asp.net MVC前后端各种交互
    存储过程实现树形目录外联其他表实现每个节点的统计
    CSS自定义右键菜单
  • 原文地址:https://www.cnblogs.com/Hades123/p/11715629.html
Copyright © 2011-2022 走看看