pydantic 基本模板

pydantic使用

pydantic的參考文檔pydantic使用

pydanitc模板

目標(biāo)檢測框

from pydantic import BaseModel, field_validator, model_validator, Field
from typing import List

class KeyPoint(BaseModel):
    x : int
    y : int

class Box(BaseModel):
    left: int
    top: int
    right: int
    bottom : int
    confidence : float = Field(..., ge=0, le=1)
    label: str
    keyPoints : List[KeyPoint] = Field(default=None)

    @field_validator("left", "top", "right", "bottom", mode='before')
    def ensure_non_negative(cls, v):
        return max(v, 0)
    
    @model_validator(mode='after')
    def ensure_correct_box(self):
        if self.left >= self.right:
            raise ValueError(f"'left' ({self.left}) must be less than 'right' ({self.right}).")
        if self.top >= self.bottom:
            raise ValueError(f"'top' ({self.top}) must be less than 'bottom' ({self.bottom}).")
        return self
    
    @property
    def width(self):
        return self.right - self.left

    @property
    def height(self):
        return self.bottom - self.top

    @property
    def area(self):
        return self.width * self.height

if __name__ == "__main__":
    box = Box(left=100, top=0, right=200, bottom=200, confidence=1.0, label="person")
    print(box)

API 返回

from pydantic import BaseModel
from typing import List, Optional, Generic, TypeVar

T = TypeVar("T")

class APIResponse(BaseModel, Generic[T]):
    success: bool
    data: Optional[List[T]]
    msg: Optional[List[str]]

# 示例用法
if __name__ == "__main__":
    response = APIResponse[dict](success=True, data=[{"key": "value"}], msg=None)
    print(response.model_dump_json())

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容