Files
knightutils/test/test_pydantic/test.py
2025-08-27 22:22:18 +08:00

35 lines
906 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 正确示例:显式类型注解
import os
from pydantic import BaseModel
class User(BaseModel):
id: int # 显式指定int类型
name: str # 显式指定str类型
is_active: bool = True # 带默认值的类型注解
# 错误示例:缺少类型注解
# class BadUser(BaseModel):
# id = 1 # 缺少类型注解Pydantic 2.9+将报错
# name = "John" # 缺少类型注解Pydantic 2.9+将报错
os.environ['app_port'] = '8888'
# 环境变量自动映射示例
from pydantic_settings import BaseSettings, SettingsConfigDict
class AppConfig(BaseSettings):
host: str = "localhost"
port: int = 8000
model_config = SettingsConfigDict(
env_prefix="APP_", # 环境变量前缀
case_sensitive=False # 不区分大小写
)
# 当环境变量存在APP_PORT=8080时
config = AppConfig()
print(config.port) # 输出: 8080 (而非默认的8000)