【问题标题】:DRF transmit errors through functionsDRF 通过函数传输错误
【发布时间】:2019-05-10 00:02:42
【问题描述】:

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

假设我们在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() 访问不可用的资源。

【问题讨论】:

  • 您的视图中已经有一个错误案例。只需添加另一个。致电other_function 并评估结果或让它引发您在视图中捕获的错误。另外,这与 DRF 有什么关系?

标签: python django error-handling django-rest-framework


【解决方案1】:

带有错误的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)

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    相关资源
    最近更新 更多