[英]How to have different permission classes for methods in DRF
I have a view similar to this:我有一个类似的观点:
from django.http import HttpResponse
from rest_framework import generics
class MyView(generics.ListCreateAPIView):
def get_queryset(self):
# <view logic>
return HttpResponse('result')
def post(self, request):
# <view logic x2>
return HttpResponse('message_post_template')
And I would like the GET request to have the permission class of IsAuthenticated
and the POST request should have a permission class of HasAPIKey
from Django REST Framework API Key .我希望 GET 请求具有
IsAuthenticated
的权限类,POST 请求应该具有来自Django REST Framework API Key的HasAPIKey
的权限类。 How can I do this?我怎样才能做到这一点?
I tried doing permission_classes = [IsAuthenticated | HasAPIKey]
我试过做
permission_classes = [IsAuthenticated | HasAPIKey]
permission_classes = [IsAuthenticated | HasAPIKey]
but that would be too lenient because it would allow the functions to work if the other permission other than the one required is available. permission_classes = [IsAuthenticated | HasAPIKey]
但这太宽松了,因为如果除所需权限之外的其他权限可用,它会允许函数工作。
from django.http import HttpResponse
from rest_framework import generics
class MyView(generics.ListCreateAPIView):
def get_permissions(self):
method = self.request.method
if method == 'POST':
return [HasAPIKey()]
else:
return [IsAuthenticated()]
def get_queryset(self):
# <view logic>
return HttpResponse('result')
def post(self, request):
# <view logic x2>
return HttpResponse('message_post_template')
Reference:参考:
https://github.com/encode/django-rest-framework/blob/dff9759555eefef67c552f175d04bb7d8381e919/rest_framework/views.py#L274 https://github.com/encode/django-rest-framework/blob/dff9759555eefef67c552f175d04bb7d8381e919/rest_framework/views.py#L274
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.