Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a variable between multiple custom permission classes in drf

I have a base permission class that two ViewSets are sharing and one other permission class each that is custom to each of the ViewSets, so 3 permissions all together, is there a way to pass a specific variable down from the base permission class to the other permission classes? My setup looks like this:

class BasePerm(permissions.BasePermission):
    def has_permission(self, request, view):
        some_var = # call an API using request variable

class Perm1(permissions.BasePermission):
    def has_permission(self, request, view):
        # get the value of some_var from BasePerm


class Perm2(permissions.BasePermission):
    def has_permission(self, request, view):
        # get the value of some_var from BasePerm


class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [BasePerm, Perm1]


class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [BasePerm, Perm2]
like image 423
hello Avatar asked Oct 15 '25 15:10

hello


1 Answers

i don't understand why you don't use mixin. For you ask:

class BasePerm(permissions.BasePermission):

    def has_permission(self, request, view):
        self.some_var = # call an API using request variable
        return True

class Perm1(BasePerm):

    def has_permission(self, request, view):
        # get the value of some_var from BasePerm
        return super().has_permission(request, view) and some_staff_with(self.some_var)


class Perm2(BasePerm):

    def has_permission(self, request, view):
        # get the value of some_var from BasePerm
        return super().has_permission(request, view) and some_other_staff_with(self.some_var)

class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [Perm1]


class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [Perm2]
like image 81
Maxim Danilov Avatar answered Oct 17 '25 04:10

Maxim Danilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!