pydantic

一个数据格式定义和校验的包

 

官方文档:  Field Types - Pydantic

 

 

基本使用test.py

# pydantic_test.py
from datetime import datetime, date
from typing import List, Optional

from pydantic.main import BaseModel, ValidationError
from pathlib import Path

from pydantic.types import constr
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base


class User(BaseModel):
    id: int
    name: str = "lqf"
    sign_time: Optional[datetime] = None
    friends: List[int] = []


data = {
    "id": "123",
    "sign_time": "2022-12-22 12:22",
    "friends": [1, 2, "3"],
}

user = User(**data)

print("\033[31m1.  --- 英文小圆点点出属性--- \033[0m")

print(f'user_id:{user.id}\n'
      f'name:{user.name}\n'
      f'sign_time:{user.sign_time}\n'
      f'friends:{user.friends}')

print("\033[31m2.  --- 校验失败处理--- \033[0m")

try:
    User(id=1, sign_time=datetime.now(), friends=[1, 2, "not num"])
except ValidationError as e:
    print(e.json())

print("\033[31m3.  --- 模型类的属性和方法--- \033[0m")

print(111, user.dict())
print(user.json())
print(user.copy())  # 浅拷贝
# 解析字典
print(User.parse_obj(obj=data))
# 解析json数据
print(User.parse_raw('{"id": "123", "name": "lqf", "sign_time": "2022-12-22T12:22:00", "friends": [1, 2, 3]}'))

file_path = Path("aaa.json")  # 实例化一个文件
# 向文件写入内容
file_path.write_text('{"id": "123", "name": "lqf", "sign_time": "2022-12-22T12:22:00", "friends": [1, 2, 3]}')
# 解析文件
print(User.parse_file(file_path))

print(user.schema())
print(user.schema_json())

# 查看类所有的字段
print(f'User_keys:\n{User.__fields__.keys()}')

print("\033[31m4.  --- 递归模型--- \033[0m")


# 在一个模型里调用另一个模型


class Sound(BaseModel):
    sound: str


class Dog(BaseModel):
    birthday: date
    weight: Optional[float] = None
    sound: List[Sound]  # 不同的狗有不同的叫声


dogs = Dog(birthday=datetime.today(), weight=6.66, sound=[
    {"sound": "wang wang ~"}, {"sound": "wang ~"},
])

print(dogs.dict())

print("\033[31m<num>.  --- 模型类的属性和方法--- \033[0m")
# 怎么从类的实例创建符合ORM对象的模型


Base = declarative_base()


# 建两张数据表

# sqlalchemy 如何定义模型表
class CompanyOrm(Base):
    __tablename__ = 'companies'
    id = Column(Integer, primary_key=True, nullable=False)
    public_key = Column(String(20), index=True, nullable=True, unique=True)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))


# pydantic定义的数据格式规范类
class CompanyMode(BaseModel):
    id: int
    public_key: constr(max_length=20)
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:
        orm_mode = True


company_orm = CompanyOrm(
    id=123,
    public_key='foo',
    name='my company',
    domains=['example', 'hello']
)

print(CompanyMode.from_orm(company_orm))

"""
1.  --- 英文小圆点点出属性--- 
user_id:123
name:lqf
sign_time:2022-12-22 12:22:00
friends:[1, 2, 3]
2.  --- 校验失败处理--- 
[
  {
    "loc": [
      "friends",
      2
    ],
    "msg": "value is not a valid integer",
    "type": "type_error.integer"
  }
]
3.  --- 模型类的属性和方法--- 
111 {'id': 123, 'name': 'lqf', 'sign_time': datetime.datetime(2022, 12, 22, 12, 22), 'friends': [1, 2, 3]}
{"id": 123, "name": "lqf", "sign_time": "2022-12-22T12:22:00", "friends": [1, 2, 3]}
id=123 name='lqf' sign_time=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
id=123 name='lqf' sign_time=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
id=123 name='lqf' sign_time=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
id=123 name='lqf' sign_time=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
{'title': 'User', 'type': 'object', 'properties': {'id': {'title': 'Id', 'type': 'integer'}, 'name': {'title': 'Name', 'default': 'lqf', 'type': 'string'}, 'sign_time': {'title': 'Sign Time', 'type': 'string', 'format': 'date-time'}, 'friends': {'title': 'Friends', 'default': [], 'type': 'array', 'items': {'type': 'integer'}}}, 'required': ['id']}
{"title": "User", "type": "object", "properties": {"id": {"title": "Id", "type": "integer"}, "name": {"title": "Name", "default": "lqf", "type": "string"}, "sign_time": {"title": "Sign Time", "type": "string", "format": "date-time"}, "friends": {"title": "Friends", "default": [], "type": "array", "items": {"type": "integer"}}}, "required": ["id"]}
User_keys:
dict_keys(['id', 'name', 'sign_time', 'friends'])
4.  --- 递归模型--- 
{'birthday': datetime.date(2024, 6, 23), 'weight': 6.66, 'sound': [{'sound': 'wang wang ~'}, {'sound': 'wang ~'}]}
<num>.  --- 模型类的属性和方法--- 
id=123 public_key='foo' name='my company' domains=['example', 'hello']
"""

 

posted @ 2024-06-23 18:47  tslam  阅读(2)  评论(0编辑  收藏  举报