Django APIView: Applying Permissions Only to POST Method
You can use the 'permission_classes' attribute on a class-based view in Django to specify which permissions should be required to access the view. This attribute can be set on the view class itself, or on specific methods within the class.
To set the 'permission_classes' attribute for the 'POST' method but not the 'GET' method, you can override the 'get_permissions' method in your view and return different permissions depending on the HTTP method. Here's an example:
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
class MyView(APIView):
def get_permissions(self):
if self.request.method == 'POST':
return [IsAuthenticated()]
else:
return []
def get(self, request):
# handle GET request
def post(self, request):
# handle POST request
In this example, the 'get_permissions' method checks the HTTP method of the request and returns different permissions depending on whether it's a 'POST' request or not. If it's a 'POST' request, the 'IsAuthenticated' permission is required. If it's not a 'POST' request (i.e. it's a 'GET' request), no permissions are required.
Note that if you want to apply the same permissions to all methods in the view, you can simply set the 'permission_classes' attribute on the view class itself, like this:
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
class MyView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
# handle GET request
def post(self, request):
# handle POST request
In this case, the 'IsAuthenticated' permission is required for both 'GET' and 'POST' requests.
原文地址: https://www.cveoy.top/t/topic/mlQ0 著作权归作者所有。请勿转载和采集!