【发布时间】:2015-10-24 07:18:35
【问题描述】:
我正在尝试在 django rest 框架中测试异常。 基于http://www.django-rest-framework.org/api-guide/exceptions/raise NotFound,
默认情况下,此异常会导致带有 HTTP 状态的响应 代码“404 未找到”。
但是,当我发出 GET(到 /example1)时,我得到一个 500 ,
Request Method: GET
Request URL: http://192.168.59.103:8002/example1
Django Version: 1.8.3
Exception Type: NotFound
Exception Value:
not found
Exception Location: /home/djangoapp/testtools/api/views.py in example1, line 7
Python Executable: /usr/bin/python
详情如下,
settings.py
REST_FRAMEWORK = {'EXCEPTION_HANDLER':'rest_framework.views.exception_handler'}
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
urls.py
from django.conf.urls import include, url
from api import views
urlpatterns = [
url(r'example1', views.example1),
]
views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.exceptions import APIException,ParseError,NotFound
def example1(request):
raise NotFound("not found")
有什么想法吗?
【问题讨论】:
-
在您对@ArpitGoyal 的回答中,您说您实际上想知道如何为任何 URL 生成您自己的 404 响应,而不仅仅是此示例代码。如果这是真的,你能澄清一下这个问题吗?
标签: django