简体   繁体   English

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

[英]Django Rest Framework custom message for 404 errors

I have a generic class based view: 我有一个基于通用类的视图:

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

And in my urls.py , I have: 在我的urls.py ,我有:

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

When the API is called with a non-existent id, it returns HTTP 404 response with the content: 当使用不存在的id调用API时,它将返回带有内容的HTTP 404响应:

{
    "detail": "Not found."
}

Is it possible to modify this response? 是否可以修改此响应?

I need to customize error message for this view only . 我只需要为此视图自定义错误消息。

This solution affect all views: 此解决方案影响所有视图:

Surely you can supply your custom exception handler: Custom exception handling 当然,您可以提供自定义异常处理程序: 自定义异常处理

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

Sure you can skip default rest_framework.views.exception_handler and make it completely raw. 当然你可以跳过默认的rest_framework.views.exception_handler并使它完全原始。

Note: remember to mention your handler in django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER'] 注意:记得在django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER']提及你的处理程序

Solution for specific view: 特定视图的解决方案:

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)

It's possible by overriding specific methods like update , retrieve as: 可以通过覆盖update等特定方法, retrieve为:

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"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM