我正在使用Django Rest Framework编写应用程序。
我创建了一个自定义权限。我为自定义权限提供了message
属性,但仍然返回了默认详细信息。
让我给你我的代码。
permissions.py
:
from annoying.functions import get_object_or_None
from rest_framework import permissions
from intquestions.models import IntQuestion
from ..models import Candidate, CandidatePickedIntChoice
CANDIDATE_ALREADY_ANSWERED = "This candidate already answered all questions."
class CandidateAnsweredQuestionsPermission(permissions.BasePermission):
"""
Permission to check if the candidate has answered all questions.
Expects candidate's email or UUID in the request's body.
"""
message = CANDIDATE_ALREADY_ANSWERED
def has_permission(self, request, view):
candidate = None
email = request.data.get("email", None)
if email:
candidate = get_object_or_None(Candidate, email=email)
else:
uuid = request.data.get("candidate", None)
if uuid:
candidate = get_object_or_None(Candidate, uuid=uuid)
if candidate:
picked_choices = CandidatePickedIntChoice.objects.filter(
candidate=candidate
).count()
total_int_questions = IntQuestion.objects.count()
if picked_choices >= total_int_questions:
return False
return True
views.py
:
from annoying.functions import get_object_or_None
from rest_framework import generics, status
from rest_framework.response import Response
from ..models import Candidate, CandidatePickedIntChoice
from .permissions import CandidateAnsweredQuestionsPermission
from .serializers import CandidateSerializer
class CandidateCreateAPIView(generics.CreateAPIView):
serializer_class = CandidateSerializer
queryset = Candidate.objects.all()
permission_classes = (CandidateAnsweredQuestionsPermission,)
def create(self, request, *args, **kwargs):
candidate = get_object_or_None(Candidate, email=request.data.get("email", None))
if not candidate:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
else:
serializer = self.get_serializer(candidate, data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
注意:我正在构建的应用可让应聘者回答问题。我之所以改写create函数,是为了使尚未完成所有问题的求职者仍然能够回答所有问题。
为什么权限消息是默认的"Authentication credentials were not provided."
而不是我自己的?
答案 0 :(得分:1)
消息Authentication credentials were not provided.
说,您 未提供凭据 。它不同于 凭据错误 消息
接下来的事情是, message
类没有属性 BasePermission
,因此除非您使用message
属性,否则它不会使用你逼。 (Source Code)
如何显示自定义PermissionDenied
消息?
从 PermissionDenied
方法的视图集(Source Code引发的permission_denied()
异常
所以你的看法应该像,
from rest_framework import exceptions
class CandidateCreateAPIView(generics.CreateAPIView):
# your code
def permission_denied(self, request, message=None):
if request.authenticators and not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=CANDIDATE_ALREADY_ANSWERED)
答案 1 :(得分:1)
Per Tom Christie(DRF的作者):
如果您不想,建议您明确提出一个
PermissionDenied
允许运行“未经身份验证与权限被拒绝”检查。
他没有继续明确提到最佳地点在哪里。在视图中似乎可以接受这个答案。但是,恕我直言,我觉得最好的选择是在自定义Permission
类本身中,因为视图可能具有多个权限,并且其中任何一个都可能失败。
这就是我的看法(为简洁起见,代码被截断了):
from rest_framework import exceptions, permissions # <-- import exceptions
CANDIDATE_ALREADY_ANSWERED = "This candidate already answered all questions."
class CandidateAnsweredQuestionsPermission(permissions.BasePermission):
message = CANDIDATE_ALREADY_ANSWERED
def has_permission(self, request, view):
if picked_choices >= total_int_questions:
raise exceptions.PermissionDenied(detail=CANDIDATE_ALREADY_ANSWERED) # <-- raise PermissionDenied here
return True
答案 2 :(得分:0)
我遇到了同样的问题,终于找到了关键点:
请勿使用任何身份验证
REST_FRAMEWORK = {
# other settings...
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
}
答案 3 :(得分:0)
我遇到了同样的问题,并且找到了解决方案,您甚至不需要AllowAny许可,只需将authentication_classes
设置为空数组即可,例如:
class TestView(generics.RetrieveAPIView):
renderer_classes = (JSONRenderer,)
permission_classes = (isSomethingElse,)
serializer_class = ProductSerializer
authentication_classes = [] # You still need to declare it even it is empty
def retrieve(self, request, *args, **kwargs):
pass
希望它仍然有帮助。