python pydantic

发布时间:2024年01月18日
# # 使用 isdigit() 方法检查整数字符串
# num_str = "12345"
# if num_str.isdigit():
#     print("字符串可以转为数字")
# else:
#     print("字符串不是数字字符串")
#
# # 使用 try-except 语句和 float() 函数检查数字字符串
# num_str = "3.14159"
# try:
#     float(num_str)
#     print("字符串可以转为数字")
# except ValueError:
#     print("字符串不是数字字符串")

from pydantic import BaseModel
from typing import Optional
from typing import Union
import json


class Position(BaseModel):
    name: str
    level: int


class Department(BaseModel):
    name: str
    desc: str
    pos: Position


class Person(BaseModel):
    # name无默认值,是必填项
    id: int
    name: str
    # name: Optional[str] # 类型为str,不填写默认设置为None
    # 无默认值可以不填
    age: int = 18 # 设置默认值
    entry_time: Union[int, str] # 两种类型都可以
    department: Department
    # position: Position


pos = Position(name="python dev", level=3)
dep = Department(name="产研部", desc="产品研发", pos=pos)

p = Person(id=1, name="Tom", age=27, entry_time="2023-10-13", department=dep)

# p = Person()
print(
    p.json())  # {"id": 1, "name": "Tom", "age": 27, "entry_time": "2023-10-13", "department": {"name": "\u4ea7\u7814\u90e8", "desc": "\u4ea7\u54c1\u7814\u53d1", "pos": {"name": "python dev", "level": 3}}}
print(
    p.dict())  # {'id': 1, 'name': 'Tom', 'age': 27, 'entry_time': '2023-10-13', 'department': {'name': '产研部', 'desc': '产品研发', 'pos': {'name': 'python dev', 'level': 3}}}
print(json.dumps(p.dict(),
                 ensure_ascii=False))  # {"id": 1, "name": "Tom", "age": 27, "entry_time": "2023-10-13", "department": {"name": "产研部", "desc": "产品研发", "pos": {"name": "python dev", "level": 3}}}
# print(p.age)

文章来源:https://blog.csdn.net/weixin_44259638/article/details/134383007
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。