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
来源:https://blog.csdn.net/qq_33801641/article/details/120320775
标签:Python,pydantic,错误处理
0
投稿
猜你喜欢
js仿百度音乐全选操作
2024-04-18 10:03:41
python list使用示例 list中找连续的数字
2022-10-16 19:49:46
WEB界面设计五种特征
2010-03-16 12:34:00
通过代码实例了解Python3编程技巧
2023-07-13 17:48:46
python 寻找优化使成本函数最小的最优解的方法
2023-03-02 16:42:39
Python网络编程之xmlrpc模块
2023-04-06 15:19:24
vue中watch的实际开发学习笔记
2024-04-30 10:41:15
1行Go代码实现反向代理的示例
2024-04-28 09:15:26
MySQL优化方案之开启慢查询日志
2024-01-23 09:30:23
Oracle 常用的SQL语句
2009-08-02 07:09:00
Python TypeError: ‘float‘ object is not subscriptable错误解决
2023-09-13 05:33:02
pycharm如何设置官方中文(如何汉化)
2022-04-27 06:20:18
将Python中的数据存储到系统本地的简单方法
2021-08-22 18:15:55
利用php+mcDropdown实现文件路径可在下拉框选择
2023-09-11 15:18:02
Mysql带And关键字的多条件查询语句
2024-01-14 08:41:17
oracle修改scott密码与解锁的方法详解
2024-01-19 19:10:40
python SVD压缩图像的实现代码
2023-04-18 18:23:30
Python的Flask框架标配模板引擎Jinja2的使用教程
2022-07-17 08:47:35
golang游戏等资源压缩包创建和操作方法
2024-04-30 10:00:22
Python中对数据库的操作详解
2024-01-19 18:26:54