from datetime import datetime from typing import List, Optional from pydantic import BaseModel, ValidationError from sqlalchemy import Column, Integer, String from sqlalchemy.dialects.postgresql import ARRAY class User(BaseModel): id: int name: str = "John Snow" create_time: Optional[datetime] = None friends: List[int] = [] external_data = { "id": "123", "create_time": "2020-12-22 12:22", "friends": [1, 2, "3"], # "3"是可以int("3")的 } user = User(**external_data) print(user.id, user.friends) print(repr(user.create_time)) print(user.dict()) try: User(id=1001, create_time=datetime.today(), friends=[1, 2, "not number"]) except ValidationError as e: print(e.json()) class CompanyOrm(Base): __tablename__ = "companies" id = Column(Integer, primary_key=True, nullable=False) public_key = Column(String(20), index=True, nullable=False, unique=True) name = Column(String(63), unique=True) domains = Column(ARRAY(String(255))) class CityInfo(BaseModel): province: str country: str is_affected: Optional[bool] = None # 与bool的区别是可以不传,默认是null