我正在学习Django Rest框架,也是django的新手。当客户端访问未找到的资源时,我希望返回json中的自定义404
错误。
我的urls.py
看起来像这样:
urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin')
]
,其中我只有一个资源,可以通过URI、http://localhost:8000/mailer/访问。
现在,当客户端访问任何其他URI (如http://localhost:8000/ )时,API应该返回一个404-Not Found
错误,如下所示:
{
"status_code" : 404
"error" : "The resource was not found"
}
如果合适的话,请用适当的代码片段建议一些答案。
发布于 2015-07-13 10:35:40
你在找handler404
。
以下是我的建议:
handler404 = path.to.your.view
添加到根URLconf中。这是如何做到的:
project.views
从django.http导入JsonResponse def custom404(request,exception=None):返回JsonResponse({ 'status_code':404,'error':‘没有找到资源’})project.urls
从project.views导入custom404 handler404 = custom404有关更多细节,请阅读错误处理。
Django REST框架例外可能也很有用。
发布于 2015-07-13 10:28:43
根据django文档: Django按照顺序遍历每个URL模式,并在与请求的URL匹配的第一个URL处停止。参考文献:https://docs.djangoproject.com/en/1.8/topics/http/urls/
因此,您可以在您创建的urlpatterns之后添加另一个url,它应该匹配所有url模式,并将它们发送到返回404代码的视图中。
即:
urlpatterns = [
url(r'^mailer/$', views.Mailer.as_view(), name='send-email-to-admin'),
url(r'^.*/$',views.Error404.as_view(),name='error404')]
发布于 2021-05-28 11:25:46
@Ernest的答案是正确的。但是,如果您使用的是同时处理浏览器页面加载和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)
https://stackoverflow.com/questions/31380280
复制相似问题