Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django rest_框架:如何将附加属性传递给异常/错误响应?_Python_Django_Django Rest Framework - Fatal编程技术网

Python Django rest_框架:如何将附加属性传递给异常/错误响应?

Python Django rest_框架:如何将附加属性传递给异常/错误响应?,python,django,django-rest-framework,Python,Django,Django Rest Framework,我将Python3.6与Django 1.11.9和rest_框架3.6.2一起使用 我有一个视图(APIView),只有成功通过给定HasunlimitedAcces权限检查的某些用户才能访问该视图。如果无法通过后者,我将提出一个PermissionDenied,并提供我选择的关于错误的详细消息,以传递到前端。到目前为止,由于“permission\u classes”decorator(是的,这里我使用的是基于函数的视图),通过将HasUnlimitedAccessPermission应用到

我将Python3.6与Django 1.11.9和rest_框架3.6.2一起使用

我有一个视图(APIView),只有成功通过给定HasunlimitedAcces权限检查的某些用户才能访问该视图。如果无法通过后者,我将提出一个PermissionDenied,并提供我选择的关于错误的详细消息,以传递到前端。到目前为止,由于“permission\u classes”decorator(是的,这里我使用的是基于函数的视图),通过将HasUnlimitedAccessPermission应用到我的视图中,所有这些都很容易实现

现在,我想要实现的是向我的错误响应JSON传递一个附加属性(当用户未能通过权限测试时)。该属性将是一个“error\u id”属性,它将使前端开发人员能够根据“error\u id”值调整错误显示。JSON响应的一个例子是:

{
    "error": "To enjoy this feature, go pick one of our pay offer!",
    "error_id": "no_unlimited_access"
}

关于如何实现这一点,您有什么想法吗?

您的问题可以使用中间件解决

我建议您构建一个自定义中间件。因此,定制中间件可以帮助您根据需要创建响应。只需在django应用程序中插入中间件即可


您可以在或

中将自定义异常定义为

from rest_framework.serializers import ValidationError
from rest_framework import status


class CustomAPIException(ValidationError):
    """
    raises API exceptions with custom messages and custom status codes
    """
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code
并在视图中用作

from rest_framework import status


def my_view(request):
    if some_condition:
        error_msg = {
            "error": "To enjoy this feature, go pick one of our pay offer!",
            "error_id": "no_unlimited_access"
        }
        raise CustomAPIException(error_msg)
来自rest\u框架导入状态
定义我的视图(请求):
如果出现以下情况:
错误消息={
“错误”:“若要享受此功能,请选择我们的支付方案!”,
“错误\u id”:“无限制访问”
}
引发CustomAPIException(错误消息)

好的,感谢Bear Brown的评论和Jerin Peter George的回答(由rest_框架源代码完成),我完成了以下工作:

1) 已创建自定义PermissionDenied异常:

class CustomPermissionDenied(PermissionDenied):

    def __init__(self, detail=None, code=None, error_id=None):
        super().__init__(detail=detail, code=code)
        self.error_id = error_id
例如,在HasUnlimitedAccessPermission中引发的:

raise CustomPermissionDenied(detail=_("To use this feature, subscribe to one of our plans."),
                             error_id="no_unlimited_access")
2) 在一个自定义的异常处理程序中(我已经有了其他用途),我在省略号之间添加了行

def custom_exception_handler(exc, context):
    ...
    error_id = getattr(exc, "error_id", None)
    if error_id is not None:
        new_response_data["error_id"] = error_id
    ...
    response.data = new_response_data

return response

这就是我想要的错误响应格式。谢谢大家的帮助

看起来你需要这可能会有帮助-谢谢你的回答和参考!是的,我可以使用中间件来实现这一目的,但通过阅读rest_框架文档,它似乎正是为我所寻找的东西而设计的。酷。我对此一无所知。让我看看。谢谢:)