0

我试图在我的 api.py 文件中使用 DEBUG = True 引发自定义错误。它抛出错误

{
"error_message": "Sorry, this request could not be processed. Please try again later."
}

这是默认的 TASTYPIE_CANNED_ERROR 消息。

我希望错误是这样的:

{"error_message": "{'id': 2671, 'error': 'Duplicate'}"}

我尝试覆盖 _handle_500 方法,但这似乎返回了我的网站 html 页面作为响应。

我得到了状态码为 400 的所需格式:

raise BadRequest({"id": int(attempt[0].id), "error": "Duplicate"})

但我需要状态码为 500。

4

1 回答 1

0

使用 ImmediateHttpResponse 并创建错误消息字典,然后将其作为响应发送。并且还需要指定 content_type="application/json"。

from django.http import HttpResponse
from tastypie.exceptions import ImmediateHttpResponse

// Build your response
response = {"error_message": {'id': 2671, 'error': 'Duplicate'}}

raise ImmediateHttpResponse(response=HttpResponse(json.dumps(response), status=401, content_type="application/json"))
于 2017-03-10T09:15:28.237 回答