官方文档以及定义 https://pydantic-docs.helpmanual.io/
Data validation and settings management using python type annotations.
使用 python 类型注释进行数据验证和设置管理。
pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.
Pydantic 在运行时强制类型提示,并在数据无效时提供用户友好的错误。
Define how data should be in pure, canonical python; validate it with pydantic.
定义纯粹的、规范的 python 中的数据应该是什么样的; 使用 pydantic 验证它。
基本的类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 from pydantic import BaseModelfrom typing import Dict , List , Sequence , Set , Tuple class Demo (BaseModel ): a: int b: float c: str d: bool e: List [int ] f: Dict [str , int ] g: Set [int ] h: Tuple [str , int ] from enum import Enumclass Gender (str , Enum): man = "man" women = "women" from typing import Optional from pydantic import BaseModelclass Person (BaseModel ): name: str age: Optional [int ] from typing import Union from pydantic import BaseModelclass Time (BaseModel ): time: Union [int , str ]
更多参考:https://pydantic-docs.helpmanual.io/usage/types/ ****
validator 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Password (BaseModel ): password: str @validator("password" ) def password_rule (cls, password ): def is_valid (password ): if len (password) < 6 or len (password) > 20 : return False if not re.search("[a-z]" , password): return False if not re.search("[A-Z]" , password): return False if not re.search("\d" , password): return False return True if not is_valid(password): raise ValueError("password is invalid" ) pw = Password(password="111222" )
更多参考:https://pydantic-docs.helpmanual.io/usage/validators/
应用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 from typing import List from pydantic import BaseModel, constrfrom sqlalchemy.dialects.postgresql import ARRAYfrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Integer, String, ColumnBase = declarative_base() class CompanyOrm (Base ): __tablename__ = 'companies' id =Column(Integer, primary_key=True , nullable=True ) public_key = Column(String(20 ), index=True , nullable=False , unique=True ) name = Column(String(100 ), unique=True ) domains = Column(ARRAY(String(255 ))) class CompanyModel (BaseModel ): id : int public_key: constr(max_length=20 ) name: constr(max_length=100 ) domains: List [constr(max_length=255 )] class Config : orm_mode = True co_orm = CompanyOrm( id =1 , public_key="akey" , name="andy" , domains=['123.com' , '456.com' ] ) print (CompanyModel.from_orm(co_orm))