pydantic_test.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from datetime import datetime
  2. from typing import List, Optional
  3. from pydantic import BaseModel, ValidationError
  4. from sqlalchemy import Column, Integer, String
  5. from sqlalchemy.dialects.postgresql import ARRAY
  6. class User(BaseModel):
  7. id: int
  8. name: str = "John Snow"
  9. create_time: Optional[datetime] = None
  10. friends: List[int] = []
  11. external_data = {
  12. "id": "123",
  13. "create_time": "2020-12-22 12:22",
  14. "friends": [1, 2, "3"], # "3"是可以int("3")的
  15. }
  16. user = User(**external_data)
  17. print(user.id, user.friends)
  18. print(repr(user.create_time))
  19. print(user.dict())
  20. try:
  21. User(id=1001, create_time=datetime.today(), friends=[1, 2, "not number"])
  22. except ValidationError as e:
  23. print(e.json())
  24. class CompanyOrm(Base):
  25. __tablename__ = "companies"
  26. id = Column(Integer, primary_key=True, nullable=False)
  27. public_key = Column(String(20), index=True, nullable=False, unique=True)
  28. name = Column(String(63), unique=True)
  29. domains = Column(ARRAY(String(255)))
  30. class CityInfo(BaseModel):
  31. province: str
  32. country: str
  33. is_affected: Optional[bool] = None # 与bool的区别是可以不传,默认是null