【发布时间】: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