欢迎来到赛兔子家园

drf权限

在drf开发中,如果有些接口必须同时满足:A条件、B条件、C条件。 有些接口只需要满足:B条件、C条件,此时就可以利用权限组件来编写这些条件。

  • 且关系,默认支持:A条件 且 B条件 且 C条件,同时满足。

需求:订单接口:http://127.0.0.1:8000/api/auth/order/需要同时满足:员工、经理、老板3种角色才能访问;

局部应用

views.py

from rest_framework.permissions import BasePermission

class UserPermission(BasePermission):
    """员工"""
    message = {"code": 1003, "msg": "无权限访问1"} # 返回信息

    def has_permission(self, request, view):
        if request.user.get("role") == 3:
            return True
        return False

class ManagerPermission(BasePermission):
    """经理"""
    message = {"code":1003,"msg":"无权限访问2"}

    def has_permission(self, request, view):
        if request.user.get("role") == 2:
            return True
        return False


class BossPermission(BasePermission):
    """老板"""
    message = {"code":1003,"msg":"无权限访问3"}

    def has_permission(self, request, view):
        if request.user.get("role") == 1:
            return True
        return  False

class OrderView(APIView):
    """需要登录接口"""
    permission_classes = [UserPermission,ManagerPermission,BossPermission] # 所有权限类都返回true才能有权限访问

     def get(self, request):
        print(request.user)
        message = f"{request.user}的订单信息"
                return Response(message)

 全局配置

utils/ext/per.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2024/3/18 17:59'
# software: PyCharm

from rest_framework.permissions import BasePermission

class UserPermission(BasePermission):
    """员工"""
    message = {"code": 1003, "msg": "无权限访问1"}

    def has_permission(self, request, view):
        if request.user.get("role") == 3:
            return True
        return False


class ManagerPermission(BasePermission):
    """经理"""
    message = {"code": 1003, "msg": "无权限访问2"}

    def has_permission(self, request, view):
        if request.user.get("role") == 2:
            return True
        return False


class BossPermission(BasePermission):
    """老板"""
    message = {"code": 1003, "msg": "无权限访问3"}

    def has_permission(self, request, view):
        if request.user.get("role") == 1:
            return True
        return False

settings.py

REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
     "DEFAULT_PERMISSION_CLASSES":[
          "ext.per.UserPermission",
          "ext.per.ManagerPermission",
          "ext.per.BossPermission",
    ]
}                        

权限组件 = [权限类,权限类,权限类..] ----> 执行所有权限类中的has_permission方法,返回True通过、返回False表示不通过。默认情况下,执行所有的权限类,保证所有的权限类中的has_permission方法都返回True 。

扩展

整改权限组件:满足任意条件:A条件、B条件、C条件 只要满足任意一个条件即可访问;

实现思路:

APIView类中check_permissions()方法重写为或关系;

APIView类check_permisssions()

  def check_permissions(self, request):
        for permission in self.get_permissions(): # 读取权限类实例对象
            if not permission.has_permission(request, self):  # 调用权限对象中has_permission()方法,只要返回False权限校验失败。且的关系
                self.permission_denied(
                    request,
                    message=getattr(permission, 'message', None),
                    code=getattr(permission, 'code', None)
                )

 重写check_permissions()

def check_permissions(self, request):
    on_permission_objects = []
    for permission in self.get_permissions():
        if permission.has_permission(request, self):  # 或关系,只要返回True,权限校验通过
            return
        else:
            on_permission_objects.append(permission)
    else:
        self.permission_denied(
            request,
            message=getattr(on_permission_objects[0], 'message', None),
            code=getattr(on_permission_objects[0], 'code', None)
        )

将重写check_permisssions()应用项目中

重写APIView类

utils/view.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2024/3/11 21:44'
# software: PyCharm

from rest_framework.views import APIView

class MyAPIView(APIView):
    def check_permissions(self, request):
        on_permission_objects = []
        for permission in self.get_permissions():
            if permission.has_permission(request, self): # 或关系,只要返回True,权限校验通过
                      returnelse:
                on_permission_objects.append(permission)
        else:
            self.permission_denied(
                request,
                message=getattr(on_permission_objects[0], 'message', None),
                code=getattr(on_permission_objects[0], 'code', None)
            )

views.py

from rest_framework.response import Response
from utils.view import MyAPIView

from utils.ext.per import ManagerPermission,BossPermission,UserPermission

class OrderView(MyAPIView):
    """需要登录接口"""
    permission_classes = [ManagerPermission,BossPermission,UserPermission]

    def get(self, request):
        print(request.user)
        message = f"{request.user}的订单信息"
        return Response(message)

urls.py

from django.urls import path

from apps.api import views

urlpatterns = [
    path('order/', views.OrderView.as_view()),

]

 

posted on 2024-03-18 20:25  赛兔子  阅读(5)  评论(0编辑  收藏  举报

导航