最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python編程pydantic觸發(fā)及訪問錯誤處理

 更新時間:2021年09月29日 09:00:48   作者:小菠蘿測試筆記  
這篇文章主要為大家介紹了Python編程中pydantic會觸發(fā)及發(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')
        # 返回傳進來的值
        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ā)及訪問錯誤處理的詳細內(nèi)容,更多關(guān)于pydantic觸發(fā)及訪問錯誤的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python實現(xiàn)圖片橫向和縱向拼接

    python實現(xiàn)圖片橫向和縱向拼接

    這篇文章主要為大家詳細介紹了python實現(xiàn)圖片橫向和縱向拼接,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • Python遍歷目錄中的所有文件的方法

    Python遍歷目錄中的所有文件的方法

    Pyhton中我們一般使用os.walk生成器來獲取文件夾中的所有文件,這里我們就來詳細看一下Python遍歷目錄中的所有文件的方法,包括一個進階的利用fnmatch模塊進行匹配的方法:
    2016-07-07
  • Python selenium 自動化腳本打包成一個exe文件(推薦)

    Python selenium 自動化腳本打包成一個exe文件(推薦)

    這篇文章主要介紹了Python selenium 自動化腳本打包成一個exe文件,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-01-01
  • python實現(xiàn)飛機大戰(zhàn)游戲(pygame版)

    python實現(xiàn)飛機大戰(zhàn)游戲(pygame版)

    這篇文章主要為大家詳細介紹了python實現(xiàn)pygame版的飛機大戰(zhàn)游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • Python中Numpy的深拷貝和淺拷貝

    Python中Numpy的深拷貝和淺拷貝

    這篇文章主要介紹了Python中Numpy的深拷貝和淺拷貝,通過講解Python中對Numpy數(shù)組操作的淺拷貝和深拷貝的概念和背后的原理展開全文,需要的小伙伴可以參考一下
    2022-05-05
  • Pycharm中無法使用pip安裝的包問題解決方案

    Pycharm中無法使用pip安裝的包問題解決方案

    本文主要介紹了Pycharm中無法使用pip安裝的包問題解決方案,在終端通過pip裝好包以后,在pycharm中導(dǎo)入包時,依然會報錯,下面就來介紹一下解決方法
    2023-09-09
  • Python實現(xiàn)區(qū)間調(diào)度算法

    Python實現(xiàn)區(qū)間調(diào)度算法

    區(qū)間調(diào)度算法是一種在給定的一組任務(wù)中,選擇盡可能多的相互不沖突的任務(wù)的算法,本文主要介紹了如何使用Python實現(xiàn)區(qū)間調(diào)度算法,有需要的可以參考下
    2024-10-10
  • Python curses內(nèi)置顏色用法實例

    Python curses內(nèi)置顏色用法實例

    在本篇文章里小編給大家整理的是一篇關(guān)于Python curses內(nèi)置顏色用法實例內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2021-06-06
  • python處理文本文件實現(xiàn)生成指定格式文件的方法

    python處理文本文件實現(xiàn)生成指定格式文件的方法

    這篇文章主要介紹了python處理文本文件實現(xiàn)生成指定格式文件的方法,有一定的實用價值,需要的朋友可以參考下
    2014-07-07
  • TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼

    TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼

    ?TensorFlow數(shù)據(jù)增強?是一種通過變換和擴充訓(xùn)練數(shù)據(jù)的方法,本文主要介紹了TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼,具有一定的參考價值,感興趣的可以了解游戲
    2024-08-08

最新評論

金昌市| 望都县| 丹棱县| 阳原县| 阜康市| 昌乐县| 晴隆县| 阿克苏市| 金川县| 东光县| 尼玛县| 晴隆县| 油尖旺区| 师宗县| 宿州市| 阿坝县| 灵山县| 酒泉市| 福建省| 宜兰市| 崇阳县| 华宁县| 神农架林区| 庆元县| 台北县| 龙川县| 无极县| 巍山| 宁阳县| 阿拉善盟| 济南市| 文安县| 西昌市| 白水县| 乌兰县| 新乐市| 长宁区| 岗巴县| 南乐县| 应用必备| 高密市|