【问题标题】:Can get_queryset return 403 or any custom responseget_queryset 能否返回 403 或任何自定义响应
【发布时间】:2021-06-27 08:36:27
【问题描述】:

我不知道这是否是这样做的好方法。
我有一个端点,它应该检索系统的特定实例。
在担心权限之前,我的视图如下所示:

类 SystemDetail(generics.RetrieveAPIView):
""" 获取系统详细信息 """
查询集 = System.objects.all()
serializer_class= 系统序列化器

我想更新它,因为我希望用户只能看到他们拥有的系统。

所以我像这样更新我的观点:

class SystemDetail(generics.RetrieveAPIView):
def get_queryset(self):
    user_groups = self.request.user.groups.all().values_list('name')

    if 'all_rights' not in user_groups[0]:
        if len(user_groups) == 1: # For now we say that 1 user is only in 1 group
            dealer_name: str = user_groups[0][0].capitalize() # Group name are creating progammatically, it is using the same enum than the dealer name on the system
            return System.objects.filter(dealer__name=dealer_name)
        else:
            raise AttributeError('User in 2 groups, endpoint can not manage it')
    else:
        return System.objects.all()

""" Get a system detail """
serializer_class = SystemSerializer

所以基本上它可以工作,当我尝试访问一个我不应该看到的系统时,我收到了这条消息:

{"detail":"未找到。"}

但我想要的是设置一条带有 403 状态的自定义消息,告诉用户他正在尝试访问他看不到的系统。

实现这一目标的好方法是什么?

谢谢。 :)

【问题讨论】:

    标签: django rest django-rest-framework permissions


    【解决方案1】:

    您可以覆盖 DRF 的 APIException 类:

    from typing import Union
    
    from rest_framework.exceptions import APIException
    from rest_framework.status import HTTP_400_BAD_REQUEST
    
    
    class CustomAPIException(APIException):
        def __init__(
            self,
            detail: Union[str, None] = None,
            code: int = HTTP_400_BAD_REQUEST,
        ) -> None:
            self.status_code = code
            super().__init__(detail, code)
    
    

    那么你就可以在你的视图中举起它:

    raise CustomAPIException(
        detail={"errorMessage": "My custom error message."},
        code=HTTP_403_FORBIDDEN,
    )
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2021-05-10
      • 2019-10-28
      • 2012-07-27
      • 2021-04-21
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多