Python编程pydantic触发及访问错误处理

作者:小菠萝测试笔记 时间:2021-05-19 20:49:07 

常见触发错误的情况

  • 如果传入的字段多了会自动过滤

  • 如果传入的少了会报错,必填字段

  • 如果传入的字段名称对不上也会报错

  • 如果传入的类型不对会自动转换

  • 如果不能转换则会报错

错误的触发

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

注意

验证代码不应该抛出 ValidationError 本身

而是应该抛出 ValueError、TypeError、AssertionError 或他们的子类

ValidationError 会包含所有错误及其发生方式的信息

访问错误的方式

e.errors() :返回输入数据中发现的错误的列表

e.json() :以 JSON 格式返回错误(推荐)

str(e) :以人类可读的方式返回错误

简单栗子


# 一定要导入 ValidationError
from pydantic import BaseModel, ValidationError
class Person(BaseModel):
   id: int
   name: str
try:
   # id是个int类型,如果不是int或者不能转换int会报错
   p = Person(id="ss", name="hallen")  
except ValidationError as e:
# 打印异常消息
   print(e.errors())

e.errors() 的输出结果


[{'loc': ('id',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}]

e.json() 的输出结果


[
 {
   "loc": [
     "id"
   ],
   "msg": "value is not a valid integer",
   "type": "type_error.integer"
 }
]

str(e) 的输出结果


1 validation error for Person
id
 value is not a valid integer (type=type_error.integer)

复杂栗子


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
)
try:
   Model(**data)
except ValidationError as e:
   print(e.json(indent=4))

输出结果


[
   {
       "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"
   }
]

value_error.missing:必传字段缺失

value_error.number.not_gt:字段值没有大于 42

type_error.integer:字段类型错误,不是 integer

自定义错误


# 导入 validator
from pydantic import BaseModel, ValidationError, validator
class Model(BaseModel):
   foo: str

# 验证器
   @validator('foo')
   def name_must_contain_space(cls, v):
       if v != 'bar':
           # 自定义错误信息
           raise ValueError('value must be bar')
       # 返回传进来的值
       return v
try:
   Model(foo="ber")
except ValidationError as e:
   print(e.json())

输出结果


[
 {
   "loc": [
     "foo"
   ],
   "msg": "value must be bar",
   "type": "value_error"
 }
]

自定义错误模板类


from pydantic import BaseModel, PydanticValueError, ValidationError, validator
class NotABarError(PydanticValueError):
   code = 'not_a_bar'
   msg_template = 'value is not "bar", got "{wrong_value}"'
class Model(BaseModel):
   foo: str

@validator('foo')
   def name_must_contain_space(cls, v):
       if v != 'bar':
           raise NotABarError(wrong_value=v)
       return v
 try:
   Model(foo='ber')
except ValidationError as e:
   print(e.json())

输出结果


[
 {
   "loc": [
     "foo"
   ],
   "msg": "value is not \"bar\", got \"ber\"",
   "type": "value_error.not_a_bar",
   "ctx": {
     "wrong_value": "ber"
   }
 }
]

PydanticValueError

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

Python编程pydantic触发及访问错误处理

来源:https://blog.csdn.net/qq_33801641/article/details/120320775

标签:Python,pydantic,错误处理
0
投稿

猜你喜欢

  • python3 循环读取excel文件并写入json操作

    2022-11-07 15:40:11
  • Python读取一个目录下所有目录和文件的方法

    2023-05-30 23:04:21
  • Python之基础函数案例详解

    2023-07-09 19:43:24
  • oracle日期分组查询的完整实例

    2023-06-26 10:14:13
  • Python 实现子类获取父类的类成员方法

    2022-01-14 00:28:17
  • pytorch_pretrained_bert如何将tensorflow模型转化为pytorch模型

    2022-04-18 18:07:58
  • Python爬取成语接龙类网站

    2022-04-09 07:29:58
  • Python+Pygame实战之24点游戏的实现

    2023-11-07 21:14:12
  • 柳永法:vbs或asp采集文章时网页编码问题

    2009-02-04 10:50:00
  • 详解go语言中sort如何排序

    2023-09-03 14:00:38
  • python datetime时间格式的相互转换问题

    2023-12-22 01:04:29
  • Python实现操作Redis的高级用法分享

    2022-07-29 04:26:29
  • Python getattr()函数使用方法代码实例

    2022-03-04 03:30:51
  • PHP根据IP判断地区名信息的示例代码

    2023-09-10 14:05:55
  • asp伪静态情况下实现的utf-8文件缓存实现代码

    2011-02-24 10:49:00
  • 从pandas一个单元格的字符串中提取字符串方式

    2022-10-14 21:24:35
  • Python闭包思想与用法浅析

    2021-08-13 03:54:54
  • SQL SERVER 建立索引

    2010-07-02 21:01:00
  • 快速一键生成Python爬虫请求头

    2022-05-21 01:00:53
  • Python生成pdf目录书签的实例方法

    2023-10-11 15:43:21
  • asp之家 网络编程 m.aspxhome.com