Python編程pydantic觸發(fā)及訪問錯(cuò)誤處理
常見觸發(fā)錯(cuò)誤的情況
- 如果傳入的字段多了會(huì)自動(dòng)過濾
- 如果傳入的少了會(huì)報(bào)錯(cuò),必填字段
- 如果傳入的字段名稱對(duì)不上也會(huì)報(bào)錯(cuò)
- 如果傳入的類型不對(duì)會(huì)自動(dòng)轉(zhuǎn)換
- 如果不能轉(zhuǎn)換則會(huì)報(bào)錯(cuò)
錯(cuò)誤的觸發(fā)
pydantic 會(huì)在它正在驗(yàn)證的數(shù)據(jù)中發(fā)現(xiàn)錯(cuò)誤時(shí)引發(fā) ValidationError
注意
驗(yàn)證代碼不應(yīng)該拋出 ValidationError 本身
而是應(yīng)該拋出 ValueError、TypeError、AssertionError 或他們的子類
ValidationError 會(huì)包含所有錯(cuò)誤及其發(fā)生方式的信息
訪問錯(cuò)誤的方式
e.errors() :返回輸入數(shù)據(jù)中發(fā)現(xiàn)的錯(cuò)誤的列表
e.json() :以 JSON 格式返回錯(cuò)誤(推薦)
str(e) :以人類可讀的方式返回錯(cuò)誤
簡(jiǎn)單栗子
# 一定要導(dǎo)入 ValidationError from pydantic import BaseModel, ValidationError class Person(BaseModel): id: int name: str try: # id是個(gè)int類型,如果不是int或者不能轉(zhuǎn)換int會(huì)報(bào)錯(cuò) p = Person(id="ss", name="hallen") except ValidationError as e: # 打印異常消息 print(e.errors())
e.errors() 的輸出結(jié)果
[{'loc': ('id',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}]
e.json() 的輸出結(jié)果
[
{
"loc": [
"id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
str(e) 的輸出結(jié)果
1 validation error for Person id value is not a valid integer (type=type_error.integer)
復(fù)雜栗子
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))
輸出結(jié)果
[
{
"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:字段類型錯(cuò)誤,不是 integer
自定義錯(cuò)誤
# 導(dǎo)入 validator
from pydantic import BaseModel, ValidationError, validator
class Model(BaseModel):
foo: str
# 驗(yàn)證器
@validator('foo')
def name_must_contain_space(cls, v):
if v != 'bar':
# 自定義錯(cuò)誤信息
raise ValueError('value must be bar')
# 返回傳進(jìn)來的值
return v
try:
Model(foo="ber")
except ValidationError as e:
print(e.json())
輸出結(jié)果
[
{
"loc": [
"foo"
],
"msg": "value must be bar",
"type": "value_error"
}
]
自定義錯(cuò)誤模板類
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())
輸出結(jié)果
[
{
"loc": [
"foo"
],
"msg": "value is not \"bar\", got \"ber\"",
"type": "value_error.not_a_bar",
"ctx": {
"wrong_value": "ber"
}
}
]
PydanticValueError
自定義錯(cuò)誤類需要繼承這個(gè)或者 PydanticTypeError

以上就是Python編程pydantic觸發(fā)及訪問錯(cuò)誤處理的詳細(xì)內(nèi)容,更多關(guān)于pydantic觸發(fā)及訪問錯(cuò)誤的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信