Django:class 基于视图,具有多个权限

Django : class based view with multiple permissions

我正在尝试创建一个基于 class 的视图,每个函数具有不同的权限。我已经在我导入的文件中创建了我的权限:

utils.py

from rest_framework.permissions import BasePermission
from rest_framework.authentication import TokenAuthentication
from rest_framework.views import APIView

class IsOwner(BasePermission):
    """
    Check if the user who made the request is owner.
    Use like that : permission_classes = [IsOwner]
    """
    def has_object_permission(self, request, view, obj):
        # if request.method in permissions.SAFE_METHODS:
        #     return True
        return obj.user == request.user

class IsAdmin(BasePermission):
    """
    Check if the user who made the request is admin.
    Use like that : permission_classes = [IsAdmin]
    """
    def has_permission(self, request, view):
        return request.user.is_admin

class BaseView(APIView):
    """
    Check if a user is authenticated
    """
    authentication_classes = [
        TokenAuthentication,
    ]

class AdminOrOwnerView(APIView):
    """
    Check if a user is admin or owner
    """
    authentication_classes = ( IsOwner | IsAdmin,)

我想用不同的方法创建一个 class。 GET 方法将允许管理员查看所有用户。 POST 方法将允许任何用户连接。

我已经为每个方法创建了序列化程序,但我无法为每个方法分配不同的权限。

这是我的 class :

class Users(APIView):

    def get(self, request):
        """Only for admin"""
        try:
            user = Users.objects.all()
        except User.DoesNotExist():
            return HttpResponse(status=404)
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request):
        """For everyone"""
        serializer = RegistrationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.error)

如何分别对每个方法应用我的权限?

提前感谢您的帮助

您只需要像这样创建权限class:

class CustomPermissionClass(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET':
            # logic for GET method
        elif request.method == 'POST'
            # logic for POST metod
        # default logic

并将其添加到您的视图中:

class Users(APIView):
    permission_classes = [CustomPermissionClass]