You can define different permission classes for different HTTP methods using the 'APIView' class in Django. To apply a permission class for a specific method, you can override the 'get_permissions' and 'post_permissions' methods.

For example, to apply a permission class only for the 'post' method but not for the 'get' method, you can define the following in your 'APIView' subclass:

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class MyAPIView(APIView):
    permission_classes = []

    def get_permissions(self):
        # apply default permission classes for GET method
        return self.permission_classes

    def post_permissions(self):
        # apply additional permission class for POST method
        return [IsAuthenticated()]

    def get(self, request):
        # handle GET request
        pass

    def post(self, request):
        # handle POST request
        pass

In this example, the 'permission_classes' attribute is set to an empty list as a default. The 'get_permissions' method returns the default permission classes for the 'get' method, which is an empty list in this case. The 'post_permissions' method returns an additional permission class 'IsAuthenticated' for the 'post' method.

When a 'get' request is made, the default permission classes will be applied. When a 'post' request is made, both the default permission classes and the additional 'IsAuthenticated' permission class will be applied.


原文地址: https://www.cveoy.top/t/topic/mlOD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录