python - 我如何跳过 token 身份验证类仅获取请求djangorest框架

标签 python django django-rest-framework

我想要为 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/

相关文章:

python - 如何避免【Errno 12】使用子进程模块导致的Cannot allocate memory错误

python - 如何在使用 django rest auth 单击链接后验证电子邮件

python - 具有额外字段的 Django Rest 框架序列化器

python 在 readline() 之后调用 read() 没有获取整个剩余文件

Python:如何在 PyQt 中从 GroupBox 取消分配布局

libtorrent-rasterbar 的 Python 绑定(bind)不起作用

python - 为什么某些 Django ORM 查询突然以消息 "Killed"结束?

python - 如何为现有项目生成 asgi.py?

Django ajax 文件上传集成到模型表单

python - 在 django rest 框架中对 pandas DataFrame 重复操作