Python編程pydantic觸發(fā)及訪問(wèn)錯(cuò)誤處理
常見(jiàn)觸發(fā)錯(cuò)誤的情況
- 如果傳入的字段多了會(huì)自動(dòng)過(guò)濾
- 如果傳入的少了會(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ā)生方式的信息
訪問(wèn)錯(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:字段值沒(méi)有大于 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)來(lái)的值 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ā)及訪問(wèn)錯(cuò)誤處理的詳細(xì)內(nèi)容,更多關(guān)于pydantic觸發(fā)及訪問(wèn)錯(cuò)誤的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python可視化大屏庫(kù)big_screen示例詳解
提到數(shù)據(jù)可視化,我們會(huì)想到 Plotly、Matplotlib、Pyecharts等可視化庫(kù),或者一些商用軟件Tableau、FineBI等等。如果你希望操作更簡(jiǎn)單、展現(xiàn)效果更強(qiáng)大,那么這款工具 big_screen 更適合2021-11-11用Python爬取英雄聯(lián)盟的皮膚詳細(xì)示例
大家好,本篇文章主要講的是用Python爬取英雄聯(lián)盟的皮膚詳細(xì)示例,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12Python的mysql數(shù)據(jù)庫(kù)的更新如何實(shí)現(xiàn)
這篇文章主要介紹了Python的mysql數(shù)據(jù)庫(kù)的更新如何實(shí)現(xiàn)的相關(guān)資料,這里提供實(shí)例代碼,幫助大家理解應(yīng)用這部分知識(shí),需要的朋友可以參考下2017-07-07如何處理Python3.4 使用pymssql 亂碼問(wèn)題
這篇文章主要介紹了如何處理Python3.4 使用pymssql 亂碼問(wèn)題的相關(guān)資料,涉及到python pymssql相關(guān)知識(shí),對(duì)此感興趣的朋友一起學(xué)習(xí)吧2016-01-01梯度下降法介紹及利用Python實(shí)現(xiàn)的方法示例
梯度下降算法是一個(gè)很基本的算法,在機(jī)器學(xué)習(xí)和優(yōu)化中有著非常重要的作用,下面這篇文章主要給大家介紹了關(guān)于利用Python實(shí)現(xiàn)梯度下降法的相關(guān)資料,對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-07-07Python實(shí)現(xiàn)樹(shù)莓派WiFi斷線自動(dòng)重連的實(shí)例代碼
實(shí)現(xiàn) WiFi 斷線自動(dòng)重連,原理是用 Python 監(jiān)測(cè)網(wǎng)絡(luò)是否斷線,如果斷線則重啟網(wǎng)絡(luò)服務(wù)。接下來(lái)給大家分享實(shí)現(xiàn)代碼,需要的朋友參考下2017-03-03Python中Flask-RESTful編寫API接口(小白入門)
這篇文章主要介紹了Python中Flask-RESTful編寫API接口(小白入門),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Python+OpenCV實(shí)現(xiàn)角度測(cè)量的示例代碼
本文介紹如何使用python語(yǔ)言實(shí)現(xiàn)角度測(cè)量,程序包括鼠標(biāo)選點(diǎn)、直線斜率計(jì)算、角度計(jì)算三個(gè)子程序和一個(gè)主程序,感興趣的可以了解一下2022-03-03Python實(shí)現(xiàn)上下文管理器的示例代碼
這篇文章主要為大家詳細(xì)介紹了Python中實(shí)現(xiàn)上下文管理器的具體方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-07-07