猿问

在 get_queryset 中返回一个 Http 响应

我在 ListAPIView 中使用 get_queryset


我想检查用户的访问令牌,在提供列表之前,我完成了以下操作,但问题是 get_query 集不返回响应,有没有办法返回响应,或者我应该使用替代方法:


这是我在 views.py 中的课程:


class ListProductsOfCategory(generics.ListAPIView):

    serializer_class = ProductSerializer

    lookup_url_kwarg = 'category_id'


    def get_queryset(self):

        # I get the token here from the headers 

        token = self.request.META.get("HTTP_TOKEN", "")

        if not token:

            return Response(

                data={

                    "message": "no token!"

                },

                status=status.HTTP_400_BAD_REQUEST

            )

        if not UserAccess.objects.filter(accessToken=token).exists():

            return Response(

                data={

                    "message": "invalid token!"

                },    

                status=status.HTTP_400_BAD_REQUEST

            )

        category_id = self.kwargs.get(self.lookup_url_kwarg)

        return Product.objects.filter(category_id=category_id)

请注意,如果我删除了与令牌相关的部分,则一切正常。


提前致谢。


上次更新后,这是回复:

慕田峪7331174
浏览 345回答 2
2回答

慕少森

如果我做对了,我不是 100%,但我相信您可以只使用 DRF 提供的常规身份验证机制。在这个特定示例中,我认为 DRF 文档的这一部分应该向您展示如何以“DRF”方式进行操作:设置身份验证方案如果您将TokenAuthentication方案添加到您的应用程序,您不需要在您的get_queryset方法中验证令牌,但您可以只使用装饰器来限制对基于函数的视图或permission_classes基于类的视图的访问:基于视图我想这是你最感兴趣的。class ListProductsOfCategory(generics.ListAPIView):    serializer_class = ProductSerializer    lookup_url_kwarg = 'category_id'    authentication_classes = (TokenAuthentication, ) # Add others if desired    permission_classes = (IsAuthenticated,)基于路由如果您只想限制对某些路线的访问(例如,仅发布或详细信息视图),那么您可以编写自己的权限类。
随时随地看视频慕课网APP

相关分类

Python
我要回答