代码之家  ›  专栏  ›  技术社区  ›  MhmdRizk

在ListAPIView中引发错误请求400异常

  •  0
  • MhmdRizk  · 技术社区  · 7 年前

    当用户未提供令牌或令牌无效时,Im试图引发400异常我的代码如下:

    from rest_framework.exceptions import APIException, PermissionDenied
    
    
    class MissingTokenException(APIException):
        status_code = 400
        default_detail = 'Your request does not contain token'
        default_code = 'no_token'
    
    
    class InvalidTokenException(APIException):
        status_code = 400
        default_detail = 'Your request contain invalid token'
        default_code = 'invalid_token'
    

    这是my views.py文件:

    class ListProductsOfCategory(generics.ListAPIView):
        serializer_class = ProductSerializer
        lookup_url_kwarg = 'category_id'
    
        def dispatch(self, *args, **kwargs):
            token = self.request.META.get("HTTP_TOKEN", "")
            if not token:
                # here I wan to raise an error saying that no token provided.
               raise MissingTokenException
            if not UserAccess.objects.filter(accessToken=token).exists():
                # here I wan to raise an error saying that token provided is not valid.
               raise InvalidTokenException
            return super().dispatch(*args, **kwargs)
    
        def get_queryset(self):
            category_id = self.kwargs.get(self.lookup_url_kwarg)
            return Product.objects.filter(category_id=category_id)
    

    enter image description here

    如果有人可以帮助我新的django和python。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Linovia    7 年前

    DRF手柄 most of its internals within the dispatch function ,包括捕获 APIException 如果你想养一个 阿皮特例 as does DRF . 请注意,您可能会错过内容协商和其他一些事情。