gpt4 book ai didi

django - Django Rest Framework中的验证码和消息

转载 作者:行者123 更新时间:2023-12-04 12:07:06 25 4
gpt4 key购买 nike

使用序列化程序中的开箱即用字段,验证错误消息如下所示:

{
"product": [
"This field must be unique."
],
"price": [
"This field is required."
]
}

但是,对于我正在编写的API,我想为每个失败的验证提供唯一的错误代码,以便客户端可以以编程方式响应验证错误,或者可以在UI中提供自己的自定义消息。理想情况下,错误json如下所示:
{
"product": [
{
"code": "unique",
"message": "This field must be unique."
}
],
"price": [
{
"code": "required",
"message": "This field is required."
}
]
}

当前使用ValidationErrors的方法使这一点变得相当困难。浏览代码,似乎当前不支持这种类型的错误报告。但是,我正在寻找一种方法来覆盖错误处理以适合该模型。

最佳答案

这个问题已经发布了很久了,所以我将在此处添加更新的答案。较新版本的DRF现在支持此功能,但仍需要一些自定义代码。使用以下技巧创建一个新的异常处理程序:

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException


def full_details_exception_handler(exc, context):
"""
This overrides the default exception handler to
include the human-readable message AND the error code
so that clients can respond programmatically.
"""
if isinstance(exc, APIException):
exc.detail = exc.get_full_details()

return exception_handler(exc, context)

然后将DRF配置为在您的设置中使用该自定义处理程序:
REST_FRAMEWORK['EXCEPTION_HANDLER'] = 'my_module.full_details_exception_handler'

如果可以在DRF本身中将此配置添加为配置选项,那就太好了,但这是一个包含错误代码的轻量级解决方案。

关于django - Django Rest Framework中的验证码和消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155758/

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