How to get OR permissions instead of AND in REST framework

前端 未结 6 1434
遇见更好的自我
遇见更好的自我 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:25

    Now DRF allows permissions to be composed using bitwise operators: & -and- and | -or-.

    From the docs:

    Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written:

    from rest_framework.permissions import BasePermission, IsAuthenticated
    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    class ReadOnly(BasePermission):
        def has_permission(self, request, view):
            return request.method in SAFE_METHODS
    
    class ExampleView(APIView):
        permission_classes = (IsAuthenticated|ReadOnly,)
    
        def get(self, request, format=None):
            content = {
                'status': 'request was permitted'
            }
            return Response(content)
    

    Edited: Please note there is a comma after IsAuthenticated|ReadOnly.

提交回复
热议问题