DRF通过函数传输错误

2024-06-02 08:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题可能已经被问过了,或者很明显,但我找不到任何关于它的信息

假设我们在views.py中有这个方法:

def my_api_view(request):
    if request.method == "POST":
        return HttpResponse(other_function())
    else:
        return HttpResponse("{UERR:%s}" % {UERR_POST_REQUEST_EXPECTED})

其中other_function()是Django应用程序之外另一目录中另一个文件中的函数:

def other_function():
    a = function1()
    b = function2()
    return function3(a,b)

问题:如果在other_function()function1()function2()function3(a,b)中出现错误,我们如何使我们的视图返回带有错误的HttpResponse?例如,如果function1()访问不可用的资源


Tags: py信息returnrequestdef错误functionpost
1条回答
网友
1楼 · 发布于 2024-06-02 08:29:11

带有错误的HttpResponse通常只是一个带有400状态码的响应(表示客户端请求有错误,而不是您的服务器)

def my_api_view(request):
    if request.method == "POST":
        return HttpResponse(other_function())
    else:
        return HttpResponse("{UERR:%s}" % {UERR_POST_REQUEST_EXPECTED}, status=400)

如果您使用的是rest框架,那么惯例是返回rest_framework.response.Response

from rest_framework.response import Response
from rest_framework import status
def my_api_view(request):
    if request.method == "POST":
        return Response(other_function())
    else:
        return Response("{UERR:%s}" % {UERR_POST_REQUEST_EXPECTED}, status=status.HTTP_400_BAD_REQUEST)

相关问题 更多 >