How to get OR permissions instead of AND in REST framework

前端 未结 6 1417
遇见更好的自我
遇见更好的自我 2021-02-05 06:45

It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes t

6条回答
  •  攒了一身酷
    2021-02-05 07:01

    I think you might be able to use django-rules library here. Link

    It is a rule based engine very similar to decision trees and it can be easily integrated with permissions_class framework of DRF.

    The best part is you can perform set operations on simple permissions and create complex permissions from them.

    Example

    >>> @rules.predicate
    >>> def is_admin(user):
    ...     return user.is_staff 
    ...
    
    
    >>> @rules.predicate
    >>> def is_object_owner(user, object):
            return object.owner == user
    

    Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates..

    is_object_editable = is_object_owner | is_admin
    

    You can use this new predicate rule is_object_editable inside your has_permissions method of permission class.

提交回复
热议问题