Python編程pydantic觸發(fā)及訪問錯誤處理
常見觸發(fā)錯誤的情況
- 如果傳入的字段多了會自動過濾
- 如果傳入的少了會報錯,必填字段
- 如果傳入的字段名稱對不上也會報錯
- 如果傳入的類型不對會自動轉換
- 如果不能轉換則會報錯
錯誤的觸發(fā)
pydantic 會在它正在驗證的數(shù)據(jù)中發(fā)現(xiàn)錯誤時引發(fā) ValidationError
注意
驗證代碼不應該拋出 ValidationError 本身
而是應該拋出 ValueError、TypeError、AssertionError 或他們的子類
ValidationError 會包含所有錯誤及其發(fā)生方式的信息
訪問錯誤的方式
e.errors() :返回輸入數(shù)據(jù)中發(fā)現(xiàn)的錯誤的列表
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觸發(fā)及訪問錯誤處理的詳細內(nèi)容,更多關于pydantic觸發(fā)及訪問錯誤的資料請關注腳本之家其它相關文章!
相關文章
Python selenium 自動化腳本打包成一個exe文件(推薦)
這篇文章主要介紹了Python selenium 自動化腳本打包成一個exe文件,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01
python實現(xiàn)飛機大戰(zhàn)游戲(pygame版)
這篇文章主要為大家詳細介紹了python實現(xiàn)pygame版的飛機大戰(zhàn)游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-02-02
Python實現(xiàn)區(qū)間調(diào)度算法
區(qū)間調(diào)度算法是一種在給定的一組任務中,選擇盡可能多的相互不沖突的任務的算法,本文主要介紹了如何使用Python實現(xiàn)區(qū)間調(diào)度算法,有需要的可以參考下2024-10-10
python處理文本文件實現(xiàn)生成指定格式文件的方法
這篇文章主要介紹了python處理文本文件實現(xiàn)生成指定格式文件的方法,有一定的實用價值,需要的朋友可以參考下2014-07-07
TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼
?TensorFlow數(shù)據(jù)增強?是一種通過變換和擴充訓練數(shù)據(jù)的方法,本文主要介紹了TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼,具有一定的參考價值,感興趣的可以了解游戲2024-08-08

