Return 在 Django Rest Framework 中找不到资源时出现自定义 404 错误

Return Custom 404 Error when resource not found in Django Rest Framework

我正在学习Django Rest Framework,也是django的新手。当客户端将访问未找到的资源时,我想 return json 中的自定义 404 错误。

我的 urls.py 看起来像这样:

urlpatterns = [
    url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin')
]

其中我只有一个资源,可以通过URI访问,http://localhost:8000/mailer/

现在,当客户端访问 http://localhost:8000/ 等任何其他 URI 时,API 应该 return 出现 404-Not Found 错误,例如这个:

{
    "status_code" : 404
    "error" : "The resource was not found"
}

如果合适,请使用适当的代码片段建议一些答案。

根据 django 文档: Django 按顺序运行每个 URL 模式,并在第一个与请求的 URL 匹配的模式处停止。参考:https://docs.djangoproject.com/en/1.8/topics/http/urls/

因此您可以在 url 模式中添加另一个 url 在您创建的模式之后,它应该匹配所有 url 模式并将它们发送到 return 404代码。

即:

urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin'),
url(r'^.*/$',views.Error404.as_view(),name='error404')]

您正在寻找 handler404.

这是我的建议:

  1. 如果 URL 模式中的 none 匹配,则创建应调用的视图。
  2. handler404 = path.to.your.view 添加到您的根 URLconf.

这是如何完成的:

  1. project.views

    from django.http import JsonResponse
    
    
    def custom404(request, exception=None):
        return JsonResponse({
            'status_code': 404,
            'error': 'The resource was not found'
        })
    
  2. project.urls

    from project.views import custom404
    
    
    handler404 = custom404
    

阅读 error handling 了解更多详情。

Django REST framework exceptions 也可能有用。

@Ernest Ten 的回答是正确的。但是,如果您使用的应用程序既处理浏览器页面加载又处理 API 作为调用,我想添加一些输入。

我为此定制了custom404函数

def custom404(request, exception=None):
    requested_html = re.search(r'^text/html', request.META.get('HTTP_ACCEPT')) # this means requesting from browser to load html
    api = re.search(r'^/api', request.get_full_path()) # usually, API URLs tend to start with `/api`. Thus this extra check. You can remove this if you want.

    if requested_html and not api:
        return handler404(request, exception) # this will handle error in the default manner

    return JsonResponse({
        'detail': _('Requested API URL not found')
    }, status=404, safe=False)

更新:

您还应该包括 在 urls.py

from django.http import JsonResponse
...other urls...
handler404 = lambda request, exception=None: JsonResponse({'error': '404: The resource was not found'}, status=404)