如何跳过仅用于get请求Django restfram的TokenAuthentication类

2024-06-16 10:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为post请求创建TokenAuthentication类。但是对于get请求,我不想要这个身份验证类。我怎样才能做到这一点?你知道吗

class EmailViewSet(viewsets.ModelViewSet):
    queryset = Email.objects.all()
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = EmailSerializer

    def create(self, request, *args, **kwargs):
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

这里确切发生的是TokenAuthentication类应用于所有类型的请求。但是我希望这个类只用于POST请求,而不是GET请求。你知道吗


Tags: 身份验证getobjectsemailstatuspostclassclasses
1条回答
网友
1楼 · 发布于 2024-06-16 10:12:53

我认为可以重写get_authenticators函数:

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    if self.request.method == "POST":
        return [TokenAuthentication()]

    return super(EmailViewSet, self).get_authenticators()

并且,从视图中删除authentication_classes。你知道吗

相关问题 更多 >