|
1 | 1 | #!/usr/bin/python3 |
2 | 2 | # -*- coding:utf-8 -*- |
3 | | -# __author__ = '__Jack__' |
| 3 | +# __author__ = "__Jack__" |
4 | 4 |
|
| 5 | +from datetime import datetime, date |
| 6 | +from pathlib import Path |
| 7 | +from typing import List |
| 8 | +from typing import Optional |
| 9 | + |
| 10 | +from pydantic import BaseModel, ValidationError |
| 11 | +from pydantic import constr |
| 12 | +from sqlalchemy import Column, Integer, String |
| 13 | +from sqlalchemy.dialects.postgresql import ARRAY |
| 14 | +from sqlalchemy.ext.declarative import declarative_base |
| 15 | + |
| 16 | +""" |
| 17 | +Data validation and settings management using python type annotations. |
| 18 | +使用Python的类型注解来进行数据校验和settings管理 |
| 19 | +
|
| 20 | +pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid. |
| 21 | +Pydantic可以在代码运行时提供类型提示,数据校验失败时提供友好的错误提示 |
| 22 | +
|
| 23 | +Define how data should be in pure, canonical python; validate it with pydantic. |
| 24 | +定义数据应该如何在纯规范的Python代码中保存,并用Pydantic验证它 |
| 25 | +""" |
| 26 | + |
| 27 | +print("\033[31m1. --- Pydantic的基本用法。Pycharm可以安装Pydantic插件 ---\033[0m") |
| 28 | + |
| 29 | + |
| 30 | +class User(BaseModel): |
| 31 | + id: int # 必须字段 |
| 32 | + name: str = "John Snow" # 有默认值,选填字段 |
| 33 | + signup_ts: Optional[datetime] = None |
| 34 | + friends: List[int] = [] # 列表中元素是int类型或者可以直接转换成int类型 |
| 35 | + |
| 36 | + |
| 37 | +external_data = { |
| 38 | + "id": "123", |
| 39 | + "signup_ts": "2020-12-22 12:22", |
| 40 | + "friends": [1, 2, "3"], # "3"是可以int("3")的 |
| 41 | +} |
| 42 | +user = User(**external_data) |
| 43 | +print(user.id, user.friends) # 实例化后调用属性 |
| 44 | +print(repr(user.signup_ts)) |
| 45 | +print(user.dict()) |
| 46 | + |
| 47 | +print("\033[31m2. --- 校验失败处理 ---\033[0m") |
| 48 | +try: |
| 49 | + User(id=1, signup_ts=datetime.today(), friends=[1, 2, "not number"]) |
| 50 | +except ValidationError as e: |
| 51 | + print(e.json()) |
| 52 | + |
| 53 | +print("\033[31m3. --- 模型类的的属性和方法 ---\033[0m") |
| 54 | +print(user.dict()) |
| 55 | +print(user.json()) |
| 56 | +print(user.copy()) # 这里是浅拷贝 |
| 57 | +print(User.parse_obj(external_data)) |
| 58 | +print(User.parse_raw('{"id": "123", "signup_ts": "2020-12-22 12:22", "friends": [1, 2, "3"]}')) |
| 59 | + |
| 60 | +path = Path('pydantic_tutorial.json') |
| 61 | +path.write_text('{"id": "123", "signup_ts": "2020-12-22 12:22", "friends": [1, 2, "3"]}') |
| 62 | +print(User.parse_file(path)) |
| 63 | + |
| 64 | +print(user.schema()) |
| 65 | +print(user.schema_json()) |
| 66 | + |
| 67 | +user_data = {"id": "error", "signup_ts": "2020-12-22 12 22", "friends": [1, 2, 3]} # id是字符串 是错误的 |
| 68 | +print(User.construct(**user_data)) # 不检验数据直接创建模型类,不建议在construct方法中传入未经验证的数据 |
| 69 | + |
| 70 | +print(User.__fields__.keys()) # 定义模型类的时候,所有字段都注明类型,字段顺序就不会乱 |
| 71 | + |
| 72 | +print("\033[31m4. --- 递归模型 ---\033[0m") |
| 73 | + |
| 74 | + |
| 75 | +class Sound(BaseModel): |
| 76 | + sound: str |
| 77 | + |
| 78 | + |
| 79 | +class Dog(BaseModel): |
| 80 | + birthday: date |
| 81 | + weight: float = Optional[None] |
| 82 | + sound: List[Sound] # 不同的狗有不同的叫声。递归模型(Recursive Models)就是指一个嵌套一个 |
| 83 | + |
| 84 | + |
| 85 | +dogs = Dog(birthday=date.today(), weight=6.66, sound=[{"sound": "wang wang ~"}, {"sound": "ying ying ~"}]) |
| 86 | +print(dogs.dict()) |
| 87 | + |
| 88 | +print("\033[31m5. --- ORM模型:从类实例创建符合ORM对象的模型 ---\033[0m") |
| 89 | + |
| 90 | +Base = declarative_base() |
| 91 | + |
| 92 | + |
| 93 | +class CompanyOrm(Base): |
| 94 | + __tablename__ = 'companies' |
| 95 | + id = Column(Integer, primary_key=True, nullable=False) |
| 96 | + public_key = Column(String(20), index=True, nullable=False, unique=True) |
| 97 | + name = Column(String(63), unique=True) |
| 98 | + domains = Column(ARRAY(String(255))) |
| 99 | + |
| 100 | + |
| 101 | +class CompanyModel(BaseModel): |
| 102 | + id: int |
| 103 | + public_key: constr(max_length=20) |
| 104 | + name: constr(max_length=63) |
| 105 | + domains: List[constr(max_length=255)] |
| 106 | + |
| 107 | + class Config: |
| 108 | + orm_mode = True |
| 109 | + |
| 110 | + |
| 111 | +co_orm = CompanyOrm( |
| 112 | + id=123, |
| 113 | + public_key='foobar', |
| 114 | + name='Testing', |
| 115 | + domains=['example.com', 'foobar.com'], |
| 116 | +) |
| 117 | + |
| 118 | +print(CompanyModel.from_orm(co_orm)) |
| 119 | + |
| 120 | +print("\033[31m6. --- 错误处理 ---\033[0m") |
| 121 | + |
| 122 | +user_data = {"id": "error", "signup_ts": "2020-12-22 12 22", "friends": [1, 2, 3]} # id是字符串 是错误的 |
| 123 | + |
| 124 | +try: |
| 125 | + User(**user_data) |
| 126 | +except ValidationError as e: |
| 127 | + print(e) |
| 128 | + print("- " * 30) |
| 129 | + print(e.json()) |
| 130 | + print("- " * 30) |
| 131 | + print(e.errors()) |
| 132 | + |
| 133 | +print("\033[31m7. --- Pydantic支撑的字段类型 ---\033[0m") # 官方文档:https://pydantic-docs.helpmanual.io/usage/types/ |
0 commit comments