gpt4 book ai didi

django - 在 Django REST 中引发异常

转载 作者:行者123 更新时间:2023-12-04 13:16:04 24 4
gpt4 key购买 nike

我正在尝试测试 django rest 框架中的异常。
基于 http://www.django-rest-framework.org/api-guide/exceptions/提高 NotFound,

By default this exception results in a response with the HTTP status code "404 Not Found".



但是,当我发出 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

详情如下,

设置.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),
]

View .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")

有任何想法吗 ?

最佳答案

from rest_framework.exceptions import NotFound

类(class) NotFound扩展自 APIException . APIException 的默认状态码是 500 Internal Server Error , 而对于 NotFound404 .

所以根据我这里的说法,您正在尝试抛出 rest framework纯 Django View 中的异常。我在这里写了一个测试用例来检查出现错误的几率是多少。猜猜想提出一个多么简单的 Django View rest framework异常不会被识别为 View 错误。但是在提供装饰器并将其声明为 API View 时,它会进入 exception_handler
所以当你这样做时:
from rest_framework.decorators import api_view

@api_view()
def example1(request):
raise NotFound('not found')

这现在被识别为 API 抛出的异常,该异常进入默认值 rest_framework EXCEPTION_HANDLER由您提供,它返回任何给定异常的响应。

它的 docstring说:

Returns the response that should be used for any given exception. By default we handle the REST framework APIException, and also Django's built-in ValidationError, Http404 and PermissionDenied exceptions. Any unhandled exceptions may return None, which will cause a 500 error to be raised.

关于django - 在 Django REST 中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com