gpt4 book ai didi

python - djangorest_framework自定义异常错误

转载 作者:行者123 更新时间:2023-12-01 01:12:17 26 4
gpt4 key购买 nike

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

Django Rest Framework Exceptions

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

设置.py

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

ImportError Exception Value:
Could not import 'project.restapi.utils.custom_exception_handler' for API setting 'EXCEPTION_HANDLER'. AttributeError: module 'project.restapi.utils' has no attribute '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.5Python-3.7.0

最佳答案

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

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

关于python - djangorest_framework自定义异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com