具有 None 值的 Pydantic 验证错误
Pydantic validation errors with None values
我有一个网络服务的返回结果,其值按原样出现(参见示例)。键不是可选的,必须包含。
2 个结果验证错误:
- 原因 -
str type expected (type=type.error.str)
- urls -
str type expected (type=type.error.str)
{ 'code': 0, 'codetext': 'blablabla', 'status': None, 'cause': None, 'urls': None }
class Result(BaseModel):
code: int
codetext: str
status: str = ""
cause: str = ""
urls: str = ""
@validator("status", "cause", "urls")
def replace_none(cls, v):
return v or "None"
第一个问题是,处理来自网络服务的 None 值并设置为 [=37 的正确方法是什么=](带单引号和 None 作为字符串)其次,为什么只有 2 个错误而不是 3 个错误?
你可以mark fields as required but optional by declaring the field optional and using ellipsis (...
) as its value。这是一个完整的简化示例,带有测试以验证它是否有效(使用 pytest <file>
执行):
import pytest
from pydantic import BaseModel, ValidationError, validator
class Result(BaseModel):
code: int
status: str | None = ...
@validator("status")
def replace_none(cls, v):
return v or "None"
def test_result():
p = Result.parse_obj({"code": 1, "status": "test status"})
assert p.code == 1
assert p.status == "test status"
def test_required_optionals():
"""Test that missing fields raise an error."""
with pytest.raises(ValidationError):
Result.parse_obj({"code": 1})
def test_required_optional_accepts_none():
"""Test that none values are accepted."""
p = Result.parse_obj(
{
"code": 0,
"status": None,
}
)
assert p.status == "None"
我有一个网络服务的返回结果,其值按原样出现(参见示例)。键不是可选的,必须包含。
2 个结果验证错误:
- 原因 -
str type expected (type=type.error.str)
- urls -
str type expected (type=type.error.str)
{ 'code': 0, 'codetext': 'blablabla', 'status': None, 'cause': None, 'urls': None }
class Result(BaseModel):
code: int
codetext: str
status: str = ""
cause: str = ""
urls: str = ""
@validator("status", "cause", "urls")
def replace_none(cls, v):
return v or "None"
第一个问题是,处理来自网络服务的 None 值并设置为 [=37 的正确方法是什么=](带单引号和 None 作为字符串)其次,为什么只有 2 个错误而不是 3 个错误?
你可以mark fields as required but optional by declaring the field optional and using ellipsis (...
) as its value。这是一个完整的简化示例,带有测试以验证它是否有效(使用 pytest <file>
执行):
import pytest
from pydantic import BaseModel, ValidationError, validator
class Result(BaseModel):
code: int
status: str | None = ...
@validator("status")
def replace_none(cls, v):
return v or "None"
def test_result():
p = Result.parse_obj({"code": 1, "status": "test status"})
assert p.code == 1
assert p.status == "test status"
def test_required_optionals():
"""Test that missing fields raise an error."""
with pytest.raises(ValidationError):
Result.parse_obj({"code": 1})
def test_required_optional_accepts_none():
"""Test that none values are accepted."""
p = Result.parse_obj(
{
"code": 0,
"status": None,
}
)
assert p.status == "None"