pydantic错误处理

错误处理

  • 每当pydantic在它正在验证的数据中发现错误时,它就会引发。ValidationError
from typing import List
from pydantic import BaseModel, ValidationError, conint


class Location(BaseModel):
    lat = 0.1
    lng = 10.1


class Model(BaseModel):
    is_required: float
    gt_int: conint(gt=42)
    list_of_ints: List[int] = None
    a_float: float = None
    recursive_model: Location = None


data = dict(
    list_of_ints=['1', 2, 'bad'],
    a_float='not a float',
    recursive_model={'lat': 4.2, 'lng': 'New York'},
    gt_int=21,
)
  • str(e):方法将返回错误的人类可读表示形式。
    5 validation errors for Model
    is_required
      field required (type=value_error.missing)
    gt_int
      ensure this value is greater than 42 (type=value_error.number.not_gt; limit_value=42)
    list_of_ints -> 2
      value is not a valid integer (type=type_error.integer)
    a_float
      value is not a valid float (type=type_error.float)
    recursive_model -> lng
      value is not a valid float (type=type_error.float)
    
  • e.errors():方法将返回在输入数据中发现的错误列表
    [{'loc': ('is_required',), 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ('gt_int',), 'msg': 'ensure this value is greater than 42', 'type': 'value_error.number.not_gt', 'ctx': {'limit_value': 42}}, {'loc': ('list_of_ints', 2), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}, {'loc': ('a_float',), 'msg': 'value is not a valid float', 'type': 'type_error.float'}, {'loc': ('recursive_model', 'lng'), 'msg': 'value is not a valid float', 'type': 'type_error.float'}]
    
  • e.json():方法将返回 的 JSON 表示形式
    
    [
      {
        "loc": [
          "is_required"
        ],
        "msg": "field required",
        "type": "value_error.missing"
      },
      {
        "loc": [
          "gt_int"
        ],
        "msg": "ensure this value is greater than 42",
        "type": "value_error.number.not_gt",
        "ctx": {
          "limit_value": 42
        }
      },
      {
        "loc": [
          "list_of_ints",
          2
        ],
        "msg": "value is not a valid integer",
        "type": "type_error.integer"
      },
      {
        "loc": [
          "a_float"
        ],
        "msg": "value is not a valid float",
        "type": "type_error.float"
      },
      {
        "loc": [
          "recursive_model",
          "lng"
        ],
        "msg": "value is not a valid float",
        "type": "type_error.float"
      }
    ]
    
posted @ 2022-06-15 17:55  fatpuffer  阅读(283)  评论(0编辑  收藏  举报