• rest-framework之权限组件


    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,]
    
        def get(self, request):
            return HttpResponse('get')
    
        def post(self, request):
            return HttpResponse('post')
    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里配置的权限类,最后用默认的权限类

  • 相关阅读:
    python 操作mysql
    python多线程
    python socket 网络编程
    nginx源码编译安装
    CentOS网卡配置文件
    使用本地yum源
    ping github 请求超时
    ping github 请求超时
    设计模式-装饰器模式
    设计模式-装饰器模式
  • 原文地址:https://www.cnblogs.com/di2wu/p/10146602.html
Copyright © 2020-2023  润新知