为了账号安全,请及时绑定邮箱和手机立即绑定

在 get_queryset 中返回一个 Http 响应

在 get_queryset 中返回一个 Http 响应

慕田峪7331174 2021-08-05 16:31:37
我在 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)请注意,如果我删除了与令牌相关的部分,则一切正常。提前致谢。上次更新后,这是回复:
查看完整描述

2 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

如果我做对了,我不是 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,)

基于路由


如果您只想限制对某些路线的访问(例如,仅发布或详细信息视图),那么您可以编写自己的权限类。


查看完整回答
反对 回复 2021-08-05
  • 2 回答
  • 0 关注
  • 319 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号