我想要为 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
请求。
最佳答案
我认为你可以重写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()
并且,从 View 中删除authentication_classes
。
关于python - 我如何跳过 token 身份验证类仅获取请求djangorest框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37405422/