无论是开发 AI 后端服务、内部效率工具,还是写日常批处理脚本,Pydantic(数据边界)+ FastAPI(HTTP 服务)+ pathlib/httpx(文件与网络自动化) 可以覆盖 90% 的真实需求,代码量极少却稳如磐石。
1. Pydantic v2:把脏数据挡在系统门外 / Pydantic v2: Strict Data Boundaries
Pydantic v2 底层用 Rust 重写,解析速度极快。它在边界处自动做类型校验、默认值填充、范围约束与 JSON 序列化——在 AI 开发中更是 Structured Outputs 的官方标配:
Powered by a Rust core, Pydantic v2 validates untrusted JSON at system boundaries with clear errors and doubles as the standard schema layer for LLM Structured Outputs:
1 | from pydantic import BaseModel, Field, field_validator |
2. 25 行 FastAPI:高性能异步接口 + 自动 Swagger 文档 / 25-Line Production FastAPI
启动后访问 http://127.0.0.1:8000/docs 直接送你一套交互式 API 文档,输入格式不对自动返回清晰 422 错误详情,彻底告别手写参数校验 if/else:
Run uv run uvicorn app:app --reload and open /docs for instant interactive Swagger UI plus automatic 422 validation errors:
1 | # app.py -> 启动命令: uv run uvicorn app:app --reload |
3. 跨平台自动化脚本铁律:pathlib 替代 os.path / Cross-Platform Automation with pathlib
写批量整理文件、处理 Markdown/CSV 的脚本时,彻底忘记 os.path.join 字符串拼接!用内置的 pathlib.Path,用 / 运算符拼路径,macOS、Linux、Windows 全部原生兼容:
Always prefer pathlib.Path over legacy os.path string manipulation—the / operator works identically on macOS, Linux, and Windows:
1 | from pathlib import Path |
掌握这三篇现代 Python 核心后,立刻前往 Python AI 实践专栏,用你刚学会的 Pydantic、asyncio、httpx 和 pytest 亲手写出可落地的 LLM 客户端、混合检索 RAG 与可控 AI Agent!
4. 权威链接 / Official Docs
- 🚀 FastAPI: FastAPI Official Tutorial
- 🛡️ Pydantic v2: Pydantic Documentation