亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁 后端開發(fā) Python教程 Pydantic:手動驗證的終結(jié)! ?

Pydantic:手動驗證的終結(jié)! ?

Nov 26, 2024 am 12:07 AM

Pydantic 是一個 Python 數(shù)據(jù)驗證和設(shè)置管理庫。它使用 Python 類型提示來驗證和解析數(shù)據(jù),確保您的代碼能夠處理正確結(jié)構(gòu)化和類型化的數(shù)據(jù)。通過利用 Python 的類似數(shù)據(jù)類的模型結(jié)構(gòu),Pydantic 可以輕松定義復雜數(shù)據(jù)的模式,并以干凈的 Python 方式自動驗證和序列化/反序列化數(shù)據(jù)。讓我們來探討一下主要功能:

數(shù)據(jù)驗證

使用 Python 的類型提示根據(jù)模式自動驗證輸入數(shù)據(jù)。

from pydantic import BaseModel, ValidationError

class User(BaseModel):
    id: int
    name: str
    email: str

# Valid input
user = User(id=1, name="John Doe", email="john@example.com")
print(user)

# Invalid input
try:
    user = User(id="not-an-integer", name="Jane", email="jane@example.com")
except ValidationError as err:
    print(err)

每當你想定義數(shù)據(jù)模型時,請使用 pydantic.BaseModel!

功能驗證

Pydantic 提供了強大的工具,不僅可以驗證數(shù)據(jù)模型,還可以驗證函數(shù)的輸入和輸出。這是使用 @validate_call 裝飾器實現(xiàn)的,允許您對函數(shù)參數(shù)和返回值強制執(zhí)行嚴格的數(shù)據(jù)驗證。如果提供的參數(shù)或返回類型與預期類型不匹配,則會引發(fā) ValidationError。

from pydantic import validate_call

@validate_call
def greet(name: str, age: int) -> str:
    return f"Hello {name}, you are {age} years old."

# Valid input
print(greet("Alice", 30))  # Output: Hello Alice, you are 30 years old.

# Invalid input
try:
    greet("Bob", "not-a-number")
except Exception as e:
    print(e)

通過在 @validate_call 中啟用 validate_return 標志,Pydantic 還將根據(jù)其帶注釋的返回類型驗證函數(shù)的返回值。這可確保函數(shù)遵循預期的輸出模式。

from pydantic import validate_call

@validate_call(validate_return=True)
def calculate_square(number: int) -> int:
    return number ** 2  # Correct return type

# Valid input and return
print(calculate_square(4))  # Output: 16

# Invalid return value
@validate_call(validate_return=True)
def broken_square(number: int) -> int:
    return str(number ** 2)  # Incorrect return type

try:
    broken_square(4)
except Exception as e:
    print(e)

解析

Pydantic 可以將復雜的嵌套結(jié)構(gòu)(包括 JSON 數(shù)據(jù))解析為模型對象。

from pydantic import BaseModel
from typing import List

class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    items: List[Item]
    total: float

# JSON-like data
data = {
    "items": [
        {"name": "Apple", "price": 1.2},
        {"name": "Banana", "price": 0.8}
    ],
    "total": 2.0
}

order = Order(**data) 
print(order) # items=[Item(name='Apple', price=1.2), Item(name='Banana', price=0.8)] total=2.0

序列化和反序列化

Pydantic 模型可以序列化為 JSON 或字典并重構(gòu)回來。

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

# Create a model instance
user = User(id=1, name="Alice", email="alice@example.com")

# Serialize to dictionary and JSON
user_dict = user.model_dump()
user_json = user.model_dump(mode='json')

print("Dictionary:", user_dict)
print("JSON:", user_json)

# Deserialize back to the model
new_user = User.model_validate(user_json)
print("Parsed User:", new_user)

靈活的驗證

數(shù)據(jù)驗證不是強制類型驗證。例如,如果您定義一個模型,其中 id、due_date 和優(yōu)先級字段分別為 int、bool 和 datetime 類型,則可以傳遞:

  • 數(shù)字字符串作為id
  • ISO-8601、UTC 或其他日期格式的字符串作為 due_date
  • 'yes'/'no'、'on'/'off'、'true'/'false'、1/0 等作為優(yōu)先級
from sensei import APIModel
from datetime import datetime


class Task(APIModel):
    id: int
    due_date: datetime
    priority: bool


task = Task(due_date='2024-10-15T15:30:00',>



<p>The result will be<br>
</p>

<pre class="brush:php;toolbar:false">Task(id=1, due_date=datetime.datetime(2024, 10, 15, 15, 30), priority=True)

自定義驗證

您還可以使用驗證器在模型中定義自定義驗證邏輯。它們允許您應(yīng)用更復雜的驗證規(guī)則,這些規(guī)則無法使用內(nèi)置類型或字段約束輕松表達。驗證器是通過 field_validator 裝飾器或 Field 對象定義的。您可以將一個或多個字段名稱傳遞給 field_validator,以確定哪些字段將使用此驗證器,或通過“*”為每個字段應(yīng)用驗證器。

輸入 import Any
從 pydantic 導入 Field、field_validator、EmailStr、BaseModel

用戶類(基礎(chǔ)模型):
    id:整數(shù)
    用戶名:str = Field(pattern=r'^w $')
    電子郵件:EmailStr
    年齡:int = Field(18,ge=14)
    is_active: 布爾 = True
    角色:列表[str]

    # 定義驗證器在內(nèi)部解析“之前”執(zhí)行
    @field_validator('角色', mode='之前')
    def _validate_roles(cls,值:任意):
        返回 value.split(',') if isinstance(value, str) else value

user = User(id=1, 用戶名='john', email='john@example.com', 角色='學生,歌手')
打?。ㄓ脩簦?>



<h2>
  
  
  開源項目
</h2>

<p>有很多由 Pydantic 支持的開源項目。讓我們探索其中最好的:</p>

<h3>
  
  
  快速API
</h3>

<p>Pydantic 最突出的用例之一是 FastAPI,這是一個使用 Python 構(gòu)建 API 的現(xiàn)代 Web 框架。 FastAPI 廣泛使用 Pydantic 模型進行請求正文驗證、查詢參數(shù)和響應(yīng)模式。</p>

  • 來源:https://github.com/fastapi/fastapi
  • 文檔:https://fastapi.tiangolo.com

Pydantic: The end of manual validations! ?

老師

FastAPI 是為構(gòu)建 API 而設(shè)計的,而 Sensei 則是為快速、輕松地包裝這些 API 而設(shè)計的。由 Sensei 提供支持的 API 客戶端可確保用戶獲得相關(guān)的數(shù)據(jù)模型,并且不會出現(xiàn)令人困惑的錯誤。

  • 來源:https://github.com/CrocoFactory/sensei
  • 文檔:https://sensei.crocofactory.dev

Pydantic: The end of manual validations! ?

SQLModel 和 Typer

SQLModelTyper 是 FastAPI 的創(chuàng)建者 Sebastián Ramírez 開發(fā)的兩個出色的項目。

SQLModel 是一個旨在簡化 Python 應(yīng)用程序中的數(shù)據(jù)庫交互的庫。 SQLModel 構(gòu)建于 SQLAlchemyPydantic 之上,將 ORM 的強大功能與數(shù)據(jù)驗證和序列化的便利性結(jié)合在一起。

  • 來源:https://github.com/fastapi/sqlmodel
  • 文檔:https://sqlmodel.tiangolo.com

Typer 是一個使用 Python 創(chuàng)建命令行界面 (CLI) 應(yīng)用程序的框架。它通過使用 Python 的類型提示自動生成用戶友好的 CLI 命令和幫助文本來簡化流程。

  • 來源:https://github.com/fastapi/typer
  • 文檔:https://typer.tiangolo.com

以上是Pydantic:手動驗證的終結(jié)! ?的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔相應(yīng)法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
如何處理Python中的API身份驗證 如何處理Python中的API身份驗證 Jul 13, 2025 am 02:22 AM

處理API認證的關(guān)鍵在于理解并正確使用認證方式。1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應(yīng)對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲密鑰信息是關(guān)鍵。

解釋Python斷言。 解釋Python斷言。 Jul 07, 2025 am 12:14 AM

Assert是Python用于調(diào)試的斷言工具,當條件不滿足時拋出AssertionError。其語法為assert條件加可選錯誤信息,適用于內(nèi)部邏輯驗證如參數(shù)檢查、狀態(tài)確認等,但不能用于安全或用戶輸入檢查,且應(yīng)配合清晰提示信息使用,僅限開發(fā)階段輔助調(diào)試而非替代異常處理。

如何一次迭代兩個列表 如何一次迭代兩個列表 Jul 09, 2025 am 01:13 AM

在Python中同時遍歷兩個列表的常用方法是使用zip()函數(shù),它會按順序配對多個列表并以最短為準;若列表長度不一致,可使用itertools.zip_longest()以最長為準并填充缺失值;結(jié)合enumerate()可同時獲取索引。1.zip()簡潔實用,適合成對數(shù)據(jù)迭代;2.zip_longest()處理不一致長度時可填充默認值;3.enumerate(zip())可在遍歷時獲取索引,滿足多種復雜場景需求。

什么是Python迭代器? 什么是Python迭代器? Jul 08, 2025 am 02:56 AM

Inpython,IteratorSareObjectSthallowloopingThroughCollectionsByImplementing_iter __()和__next __()。1)iteratorsWiaTheIteratorProtocol,使用__ITER __()toreTurnterateratoratoranteratoratoranteratoratorAnterAnteratoratorant antheittheext__()

什么是Python型提示? 什么是Python型提示? Jul 07, 2025 am 02:55 AM

typeHintsInpyThonsolverbromblemboyofambiguityandPotentialBugSindyNamalytyCodeByallowingDevelopsosteSpecefectifyExpectedTypes.theyenhancereadability,enablellybugdetection,andimprovetool.typehintsupport.typehintsareadsareadsareadsareadsareadsareadsareadsareadsareaddedusidocolon(

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創(chuàng)建現(xiàn)代高效的API,推薦使用FastAPI;其基于標準Python類型提示,可自動生成文檔,性能優(yōu)越。安裝FastAPI和ASGI服務(wù)器uvicorn后,即可編寫接口代碼。通過定義路由、編寫處理函數(shù)并返回數(shù)據(jù),可以快速構(gòu)建API。FastAPI支持多種HTTP方法,并提供自動生成的SwaggerUI和ReDoc文檔系統(tǒng)。URL參數(shù)可通過路徑定義捕獲,查詢參數(shù)則通過函數(shù)參數(shù)設(shè)置默認值實現(xiàn)。合理使用Pydantic模型有助于提升開發(fā)效率和準確性。

設(shè)置并使用Python虛擬環(huán)境 設(shè)置并使用Python虛擬環(huán)境 Jul 06, 2025 am 02:56 AM

虛擬環(huán)境能隔離不同項目的依賴。使用Python自帶的venv模塊創(chuàng)建,命令為python-mvenvenv;激活方式:Windows用env\Scripts\activate,macOS/Linux用sourceenv/bin/activate;安裝包使用pipinstall,生成需求文件用pipfreeze>requirements.txt,恢復環(huán)境用pipinstall-rrequirements.txt;注意事項包括不提交到Git、每次新開終端需重新激活、可用IDE自動識別切換。

如何用Python測試API 如何用Python測試API Jul 12, 2025 am 02:47 AM

要測試API需使用Python的Requests庫,步驟為安裝庫、發(fā)送請求、驗證響應(yīng)、設(shè)置超時與重試。首先通過pipinstallrequests安裝庫;接著用requests.get()或requests.post()等方法發(fā)送GET或POST請求;然后檢查response.status_code和response.json()確保返回結(jié)果符合預期;最后可添加timeout參數(shù)設(shè)置超時時間,并結(jié)合retrying庫實現(xiàn)自動重試以增強穩(wěn)定性。

See all articles