如果权限为False,如何在DRF中提供自定义权限响应

时间:2019-09-06 06:55:41

标签: django-rest-framework

在权限被拒绝的情况下,我想提供相同的自定义响应。请参考上面提到的代码。

所以我有一个custom_response类,下面是我用来作为响应返回的类。

true

我还有一个VendorPermission类,如下所示。

def custom_response(data: object, errors: object, message: object = '', status_code: object = HTTP_200_OK) -> object:
    return Response(
        {"data": data,
         "error": errors,
         "message": message,
         "status": status_code
         },
        status=HTTP_200_OK
    )

并在下面的视图中使用它们。

class VendorPermission(permissions.BasePermission):
    message = "You are not authorised to access this Vendor's data.."

    def has_object_permission(self, request, view, obj):
        print(obj,'hereperm',self,view,request)
        vendor = Vendor_Info.objects.get(pk=view.kwargs['id'])
        return vendor.user == request.user

即使在权限被拒绝的情况下,我也想这样返回class CloseVendor(APIView): authentication_classes = [JSONWebTokenAuthentication] permission_classes = [VendorPermission] def get(self, request, *args, **kwargs): try: vendor_obj = Vendor_Info.objects.get( id=self.kwargs['id'] ) self.check_object_permissions(self.request, vendor_obj) status_code=HTTP_200_OK) vendor_obj.status = False vendor_obj.save() return custom_response('', '', message='Success', status_code=HTTP_200_OK) except Vendor_Info.DoesNotExist: return custom_response('', '', message='Vendor does not exist', status_code=HTTP_404_NOT_FOUND)

0 个答案:

没有答案