我是django rest_framework的新手,并试图在django中创建自定义的错误响应!。
Django Rest Framework Exceptions
经历了这些之后,一切似乎都非常简单,但是当我尝试添加自定义异常时,导入错误就会增加。
Settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler'
}
ImportError 异常值:
无法为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
model.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
答案 0 :(得分:1)
由于您的custom_exception_handler
驻留在名为custom_exception_handler.py
的文件中。您可以尝试将EXCEPTION_HANDLER
设置更改为此:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'project.restapi.utils.custom_exception_handler.custom_exception_handler'
}