Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

TypeError: unsupported operand type(s) for &: 'str' and 'str'

So,

How can I use combined permission as global permission using DEFAULT_PERMISSION_CLASSES ?

like image 353
JPG Avatar asked Sep 06 '25 03:09

JPG


1 Answers

I created a new variable by combining those classes and referenced the same in the 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.
like image 60
JPG Avatar answered Sep 07 '25 16:09

JPG