简体   繁体   English

如何在 DRF 的 DEFAULT_PERMISSION_CLASSES 中使用逻辑运算符?

[英]How to use logical operators in DRF's DEFAULT_PERMISSION_CLASSES?

Since DRF==3.9--(release notes) we have got an option to combine/compose the permission classes in our views.由于DRF==3.9--(发行说明) ,我们可以选择在我们的视图中组合/组合权限类。

class MyViewSet(...):
    permission_classes = [FooPermission & BarPermission]

I did try something like this,我确实尝试过这样的事情,

REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': (

        'utils.permissions.FooPermission' & 'utils.permissions.BarPermission',

    ),

    # other settings

}

and python raised exception和 python 引发异常

TypeError: unsupported operand type(s) for &: 'str' and 'str'类型错误:&:“str”和“str”不支持的操作数类型

So,所以,

How can I use combined permission as global permission using DEFAULT_PERMISSION_CLASSES ?如何使用DEFAULT_PERMISSION_CLASSES将组合权限用作全局权限?

I created a new variable by combining those classes and referenced the same in the DEFAULT_PERMISSION_CLASSES ,我通过组合这些类创建了一个新变量,并在DEFAULT_PERMISSION_CLASSES中引用了相同的变量,

# utils/permissions.py

from rest_framework.permissions import BasePermission


class FooPermission(BasePermission):

    def has_permission(self, request, view):
        # check permissions

        return ...


class BarPermission(BasePermission):

    def has_permission(self, request, view):
        # check permissions

        return ...


CombinedPermission = FooPermission & BarPermission

# settings.py

REST_FRAMEWORK = {

    'DEFAULT_PERMISSION_CLASSES': (

        'utils.permissions.CombinedPermission',

    ),

    # other settings

}

Note笔记

  • You can use "any supported" bitwise operators instead of & in this example.在此示例中,您可以使用“任何支持的”位运算符而不是&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更改当前视图的权限以覆盖 django rest-framework 中的 DEFAULT_PERMISSION_CLASSES - how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework “DEFAULT_PERMISSION_CLASSES 仅适用于没有明确设置权限的视图或对象。” 意思是? - What does "DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set." mean? 如何在 python 中使用逻辑运算符 - How to use logical operators in python 如何为 DRF 中的方法设置不同的权限类 - How to have different permission classes for methods in DRF 如何使用numpy.where与逻辑运算符 - How to use numpy.where with logical operators 如何在 while 循环中使用逻辑运算符? - How to use logical operators in a while loop? 切片numpy数组时使用python的逻辑运算符 - Use of python's logical operators when slicing a numpy array Python-如何对两个二进制numpy数组进行NOT,OR或使用其他逻辑运算符 - Python - How to NOT, OR and use other logical operators on two binary numpy arrays Django DRF:@permission_classes 不起作用 - Django DRF: @permission_classes not working Django DRF @permission_classes 不适用于 IsAdminUser 权限 - Django DRF @permission_classes not working for IsAdminUser permission
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM