欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年09月29日 09:00:48   作者:小菠蘿測試筆記  
這篇文章主要為大家介紹了Python編程中pydantic會觸發(fā)及發(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實現(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中導入包時,依然會報錯,下面就來介紹一下解決方法
    2023-09-09
  • Python實現(xiàn)區(qū)間調(diào)度算法

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

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

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

    在本篇文章里小編給大家整理的是一篇關于Python curses內(nèi)置顏色用法實例內(nèi)容,有興趣的朋友們可以學習下。
    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ù)增強?是一種通過變換和擴充訓練數(shù)據(jù)的方法,本文主要介紹了TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼,具有一定的參考價值,感興趣的可以了解游戲
    2024-08-08

最新評論