Python編程pydantic觸發(fā)及訪問錯誤處理
常見觸發(fā)錯誤的情況
- 如果傳入的字段多了會自動過濾
- 如果傳入的少了會報錯,必填字段
- 如果傳入的字段名稱對不上也會報錯
- 如果傳入的類型不對會自動轉(zhuǎn)換
- 如果不能轉(zhuǎn)換則會報錯
錯誤的觸發(fā)
pydantic 會在它正在驗證的數(shù)據(jù)中發(fā)現(xiàn)錯誤時引發(fā) ValidationError
注意
驗證代碼不應(yīng)該拋出 ValidationError 本身
而是應(yīng)該拋出 ValueError、TypeError、AssertionError 或他們的子類
ValidationError 會包含所有錯誤及其發(fā)生方式的信息
訪問錯誤的方式
e.errors()
:返回輸入數(shù)據(jù)中發(fā)現(xiàn)的錯誤的列表
e.json()
:以 JSON 格式返回錯誤(推薦)
str(e)
:以人類可讀的方式返回錯誤
簡單栗子
# 一定要導(dǎo)入 ValidationError from pydantic import BaseModel, ValidationError class Person(BaseModel): id: int name: str try: # id是個int類型,如果不是int或者不能轉(zhuǎn)換int會報錯 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:字段類型錯誤,不是 integer
自定義錯誤
# 導(dǎo)入 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') # 返回傳進(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" } ]
自定義錯誤模板類
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
自定義錯誤類需要繼承這個或者 PydanticTypeError
以上就是Python編程pydantic觸發(fā)及訪問錯誤處理的詳細(xì)內(nèi)容,更多關(guān)于pydantic觸發(fā)及訪問錯誤的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
用Python爬取英雄聯(lián)盟的皮膚詳細(xì)示例
大家好,本篇文章主要講的是用Python爬取英雄聯(lián)盟的皮膚詳細(xì)示例,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12Python的mysql數(shù)據(jù)庫的更新如何實現(xiàn)
這篇文章主要介紹了Python的mysql數(shù)據(jù)庫的更新如何實現(xiàn)的相關(guān)資料,這里提供實例代碼,幫助大家理解應(yīng)用這部分知識,需要的朋友可以參考下2017-07-07Python實現(xiàn)樹莓派WiFi斷線自動重連的實例代碼
實現(xiàn) WiFi 斷線自動重連,原理是用 Python 監(jiān)測網(wǎng)絡(luò)是否斷線,如果斷線則重啟網(wǎng)絡(luò)服務(wù)。接下來給大家分享實現(xiàn)代碼,需要的朋友參考下2017-03-03Python中Flask-RESTful編寫API接口(小白入門)
這篇文章主要介紹了Python中Flask-RESTful編寫API接口(小白入門),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Python+OpenCV實現(xiàn)角度測量的示例代碼
本文介紹如何使用python語言實現(xiàn)角度測量,程序包括鼠標(biāo)選點、直線斜率計算、角度計算三個子程序和一個主程序,感興趣的可以了解一下2022-03-03