当前位置:   article > 正文

Python - pydantic(3)错误处理

pydanticusererror: the `field` and `config` parameters are not available in

常见触发错误的情况

  • 如果传入的字段多了会自动过滤
  • 如果传入的少了会报错,必填字段
  • 如果传入的字段名称对不上也会报错
  • 如果传入的类型不对会自动转换,如果不能转换则会报错

错误的触发

pydantic 会在它正在验证的数据中发现错误时引发 ValidationError

注意
  • 验证代码不应该抛出 ValidationError 本身
  • 而是应该抛出 ValueError、TypeError、AssertionError 或他们的子类
  • ValidationError 会包含所有错误及其发生方式的信息

访问错误的方式

  • e.errors():返回输入数据中发现的错误的列表
  • e.json():以 JSON 格式返回错误(推荐)
  • str(e):以人类可读的方式返回错误

简单栗子

  1. # 一定要导入 ValidationError
  2. from pydantic import BaseModel, ValidationError
  3. class Person(BaseModel):
  4. id: int
  5. name: str
  6. try:
  7. # id是个int类型,如果不是int或者不能转换int会报错
  8. p = Person(id="ss", name="hallen")
  9. except ValidationError as e:
  10.   # 打印异常消息
  11. print(e.errors())
e.errors() 的输出结果
[{'loc': ('id',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}]
e.json() 的输出结果
  1. [
  2. {
  3. "loc": [
  4. "id"
  5. ],
  6. "msg": "value is not a valid integer",
  7. "type": "type_error.integer"
  8. }
  9. ]
str(e) 的输出结果
  1. 1 validation error for Person
  2. id
  3. value is not a valid integer (type=type_error.integer)

复杂栗子

  1. class Location(BaseModel):
  2. lat = 0.1
  3. lng = 10.1
  4. class Model(BaseModel):
  5. is_required: float
  6. gt_int: conint(gt=42)
  7. list_of_ints: List[int] = None
  8. a_float: float = None
  9. recursive_model: Location = None
  10. data = dict(
  11. list_of_ints=['1', 2, 'bad'],
  12. a_float='not a float',
  13. recursive_model={'lat': 4.2, 'lng': 'New York'},
  14. gt_int=21
  15. )
  16. try:
  17. Model(**data)
  18. except ValidationError as e:
  19. print(e.json(indent=4))
输出结果
  1. [
  2. {
  3. "loc": [
  4. "is_required"
  5. ],
  6. "msg": "field required",
  7. "type": "value_error.missing"
  8. },
  9. {
  10. "loc": [
  11. "gt_int"
  12. ],
  13. "msg": "ensure this value is greater than 42",
  14. "type": "value_error.number.not_gt",
  15. "ctx": {
  16. "limit_value": 42
  17. }
  18. },
  19. {
  20. "loc": [
  21. "list_of_ints",
  22. 2
  23. ],
  24. "msg": "value is not a valid integer",
  25. "type": "type_error.integer"
  26. },
  27. {
  28. "loc": [
  29. "a_float"
  30. ],
  31. "msg": "value is not a valid float",
  32. "type": "type_error.float"
  33. },
  34. {
  35. "loc": [
  36. "recursive_model",
  37. "lng"
  38. ],
  39. "msg": "value is not a valid float",
  40. "type": "type_error.float"
  41. }
  42. ]
  • value_error.missing:必传字段缺失
  • value_error.number.not_gt:字段值没有大于 42
  • type_error.integer:字段类型错误,不是 integer

自定义错误

  1. # 导入 validator
  2. from pydantic import BaseModel, ValidationError, validator
  3. class Model(BaseModel):
  4. foo: str
  5. # 验证器
  6. @validator('foo')
  7. def name_must_contain_space(cls, v):
  8. if v != 'bar':
  9. # 自定义错误信息
  10. raise ValueError('value must be bar')
  11. # 返回传进来的值
  12. return v
  13. try:
  14. Model(foo="ber")
  15. except ValidationError as e:
  16. print(e.json())
输出结果
  1. [
  2. {
  3. "loc": [
  4. "foo"
  5. ],
  6. "msg": "value must be bar",
  7. "type": "value_error"
  8. }
  9. ]

自定义错误模板类

  1. from pydantic import BaseModel, PydanticValueError, ValidationError, validator
  2. class NotABarError(PydanticValueError):
  3. code = 'not_a_bar'
  4. msg_template = 'value is not "bar", got "{wrong_value}"'
  5. class Model(BaseModel):
  6. foo: str
  7. @validator('foo')
  8. def name_must_contain_space(cls, v):
  9. if v != 'bar':
  10. raise NotABarError(wrong_value=v)
  11. return v
  12. try:
  13. Model(foo='ber')
  14. except ValidationError as e:
  15. print(e.json())
输出结果
  1. [
  2. {
  3. "loc": [
  4. "foo"
  5. ],
  6. "msg": "value is not \"bar\", got \"ber\"",
  7. "type": "value_error.not_a_bar",
  8. "ctx": {
  9. "wrong_value": "ber"
  10. }
  11. }
  12. ]
PydanticValueError

自定义错误类需要继承这个或者 PydanticTypeError

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/614830
推荐阅读
相关标签
  

闽ICP备14008679号