【问题标题】:django rest_framework custom exception errordjango rest_framework 自定义异常错误
【发布时间】:2019-07-11 03:22:41
【问题描述】:

我是 django rest_framework 的新手,并尝试在 django 中创建自定义错误响应!。

Django Rest Framework Exceptions

完成之后,一切似乎都非常简单,但是当我尝试添加自定义异常时会出现导入错误。

Settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'
}

导入错误 异常值:
无法为 API 设置“EXCEPTION_HANDLER”导入“project.restapi.utils.custom_exception_handler”。 AttributeError:模块“project.restapi.utils”没有属性“custom_exception_handler”

custom_exception_handler.py

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    return response

模型.py

class Users(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(Users, self).retrieve(request, *args, **kwargs) 

        response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0"}
        # customize the response data
        if response is not None:
            return response
        else:
            # return response with this custom representation
            response.data = {"collection": {"data": response.data},"statusCode":response.status_code,"version":"1.0","error":response.exception}
            return response

所以在上述模型上工作正常,除非我尝试点击不在数据库中的用户应该引发错误 - 未找到,所以我尝试自定义未找到对我自己有意义。就是这样

我试图整理,但很难做到!,

Django 版本:2.1.5 Python - 3.7.0

【问题讨论】:

  • 这可能是导入/模块问题。您应该在问题中包含 project.restapi.utils 的内容。没有它,很难说出问题所在。您可能需要在该文件夹中有一个__init__.py 文件并在那里导入custom_exception_handler
  • 贴出了custom_exception_handler.py代码,

标签: python django django-rest-framework


【解决方案1】:

因为您的 custom_exception_handler 位于名为 custom_exception_handler.py 的文件中。您可以尝试将EXCEPTION_HANDLER 设置更改为:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler.custom_exception_handler'
}

【讨论】:

  • DRF's setting implementation 会尝试从project.restapi.utils.custom_exception_handler 导入custom_exception_handler 函数(即最后一个点之后的部分)。在您的尝试中,它试图从 project.restapi.utils 导入 custom_exception_handler 函数。
  • (val, setting_name, e.__class__.__name__, e) 这实际上很重要!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
相关资源
最近更新 更多