4

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 ?

JPG
  • 82,442
  • 19
  • 127
  • 206

1 Answers1

3

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.
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    Fantastic! Note that this is also possible `DebugApiPermissions = (IsAuthenticated | IsLocalRequest) & DjangoModelPermissions` – Jurrian Oct 02 '20 at 16:56