404 错误的 Django Rest Framework 自定义消息



我有一个基于通用类的观点:

class ProjectDetails(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
generics.GenericAPIView):
queryset = Project.objects.all()
# Rest of definition

在我的urls.py中,我有:

urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', views.ProjectDetails.as_view())
]

当使用不存在的 id 调用 API 时,它会返回包含以下内容HTTP 404响应:

{
"detail": "Not found."
}

是否可以修改此响应?

只需要为此视图自定义错误消息。

此解决方案会影响所有视图:

当然,您可以提供自定义异常处理程序:自定义异常处理

from rest_framework.views import exception_handler
from rest_framework import status
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.status_code == status.HTTP_404_NOT_FOUND:
response.data['custom_field'] = 'some_custom_value'
return response

当然,您可以跳过默认rest_framework.views.exception_handler并使其完全原始。

注意:请记住在django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER']中提及您的处理程序

特定视图的解决方案:

from rest_framework.response import Response
# rest of the imports
class ProjectDetails(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
generics.GenericAPIView):
queryset = Project.objects.all()
def handle_exception(self, exc):
if isinstance(exc, Http404):
return Response({'data': 'your custom response'}, 
status=status.HTTP_404_NOT_FOUND)
return super(ProjectDetails, self).handle_exception(exc)

可以通过覆盖特定方法(如updateretrieve为:

from django.http import Http404
from rest_framework.response import Response

class ProjectDetails(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
generics.GenericAPIView):
queryset = Project.objects.all()
def retrieve(self, request, *args, **kwargs):
try:
return super().retrieve(request, *args, **kwargs)
except Http404:
return Response(data={"cusom": "message"})
def update(self, request, *args, **kwargs):
try:
return super().update(request, *args, **kwargs)
except Http404:
return Response(data={"cusom": "message"})

相关内容

  • 没有找到相关文章

最新更新