3. Python 环境准备:Python 3.10+ 安装、虚拟环境创建、依赖管理(pip/poetry)、项目结构初始化

在开始编写催收 API 熔断代码之前,必须搭建一个干净、可复现的 Python 开发环境。本章将指导你完成从 Python 解释器安装到项目骨架初始化的全过程,确保后续所有熔断逻辑、测试脚本和部署配置都在一致的环境中运行。

3.1 Python 3.10+ 安装与验证

催收 API 熔断机制依赖 Python 3.10 引入的 match 语句和更精确的类型注解,因此最低版本要求为 3.10。推荐使用 3.11 或 3.12 以获得更好的性能与异步支持。

操作系统 安装方式 验证命令
Windows 从 python.org 下载安装包,勾选 "Add Python to PATH" python --version
macOS brew install python@3.11 python3 --version
Linux (Ubuntu/Debian) sudo apt install python3.11 python3.11-venv python3.11 --version
版本检查要点: 确保输出为 Python 3.10.x、3.11.x 或 3.12.x。如果系统默认 Python 版本低于 3.10,请使用 python3.11 等显式命令,不要覆盖系统默认解释器。

3.2 虚拟环境创建

虚拟环境隔离项目依赖,避免不同项目之间的包版本冲突。对于催收 API 熔断项目,推荐使用 Python 内置的 venv 模块或 virtualenv。

3.2.1 使用 venv 创建

# 创建虚拟环境(在项目根目录下执行)
python3.11 -m venv venv

# 激活虚拟环境
# Linux/macOS:
source venv/bin/activate

# Windows (CMD):
venv\Scripts\activate.bat

# Windows (PowerShell):
venv\Scripts\Activate.ps1

# 验证激活成功(应显示 (venv) 前缀)
which python   # Linux/macOS
where python   # Windows

3.2.2 使用 virtualenv(备选)

pip install virtualenv
virtualenv venv --python=python3.11
source venv/bin/activate
常见陷阱: 不要将虚拟环境目录 venv/ 提交到 Git 仓库。务必在项目根目录创建 .gitignore 文件,并添加 venv/、__pycache__/、*.pyc 等条目。

3.3 依赖管理:pip 与 poetry

催收 API 熔断项目需要管理多个依赖包,包括 fastapi(API 框架)、redis(熔断状态存储)、pytest(测试)等。我们提供两种管理方式:pip + requirements.txt(轻量)和 poetry(企业级)。

3.3.1 方式一:pip + requirements.txt

# 激活虚拟环境后,安装核心依赖
pip install fastapi uvicorn redis aioredis pybreaker

# 安装开发依赖
pip install pytest pytest-asyncio httpx black isort mypy

# 导出依赖清单
pip freeze > requirements.txt

# 从 requirements.txt 恢复环境
pip install -r requirements.txt

3.3.2 方式二:poetry(推荐)

# 安装 poetry(全局)
curl -sSL https://install.python-poetry.org | python3 -

# 在项目目录初始化
poetry init --name circuit-breaker-api --description "催收API熔断机制实战项目" --python "^3.11"

# 添加核心依赖
poetry add fastapi uvicorn redis aioredis pybreaker

# 添加开发依赖
poetry add --dev pytest pytest-asyncio httpx black isort mypy

# 安装所有依赖
poetry install

# 进入 poetry 虚拟环境
poetry shell
对比维度 pip + requirements.txt poetry
依赖锁定 手动 pip freeze,易遗漏 自动生成 poetry.lock,精确锁定
依赖分组 需手动拆分多个 requirements 文件 原生支持 --dev 分组
虚拟环境管理 需手动创建/激活 venv 自动创建,poetry shell 一键进入
发布支持 无 内置 poetry build 和 publish
学习成本 低 中
课程推荐: 本课程后续所有示例均基于 poetry 管理。如果你更熟悉 pip,也可以使用 requirements.txt,但请确保版本与课程一致。

3.4 项目结构初始化

一个结构清晰的项目骨架是熔断机制可维护性的基础。下面是我们为催收 API 熔断项目设计的标准目录结构。

circuit-breaker-api/
├── README.md                 # 项目说明文档
├── pyproject.toml            # poetry 配置文件(或 requirements.txt)
├── poetry.lock               # 依赖锁定文件(poetry 自动生成)
├── .gitignore                # Git 忽略规则
├── .env.example              # 环境变量模板
├── src/                      # 源代码目录
│   ├── __init__.py
│   ├── main.py               # FastAPI 应用入口
│   ├── config.py             # 配置管理(环境变量读取)
│   ├── circuit_breaker/      # 熔断器核心模块
│   │   ├── __init__.py
│   │   ├── base.py           # 熔断器抽象基类
│   │   ├── state.py          # 状态管理(关闭/打开/半开)
│   │   ├── storage.py        # 状态存储(Redis/内存)
│   │   └── decorator.py      # 熔断装饰器
│   ├── api/                  # API 路由层
│   │   ├── __init__.py
│   │   ├── routes.py         # 催收相关接口
│   │   └── middleware.py     # 熔断中间件
│   ├── services/             # 业务逻辑层
│   │   ├── __init__.py
│   │   ├── collection.py     # 催收核心逻辑
│   │   └── external.py       # 外部催收系统调用
│   └── models/               # 数据模型
│       ├── __init__.py
│       └── schemas.py        # Pydantic 模型
├── tests/                    # 测试目录
│   ├── __init__.py
│   ├── conftest.py           # pytest 夹具
│   ├── test_circuit_breaker/ # 熔断器单元测试
│   │   ├── __init__.py
│   │   └── test_state.py
│   └── test_api/             # API 集成测试
│       ├── __init__.py
│       └── test_routes.py
└── scripts/                  # 运维脚本
    ├── start.sh              # 启动脚本
    └── seed_data.py          # 测试数据初始化
初始化命令速查:
# 创建目录结构(Linux/macOS)
mkdir -p circuit-breaker-api/{src/{circuit_breaker,api,services,models},tests/{test_circuit_breaker,test_api},scripts}

# 创建空 __init__.py 文件
touch circuit-breaker-api/src/__init__.py
touch circuit-breaker-api/src/circuit_breaker/__init__.py
touch circuit-breaker-api/src/api/__init__.py
touch circuit-breaker-api/src/services/__init__.py
touch circuit-breaker-api/src/models/__init__.py
touch circuit-breaker-api/tests/__init__.py
touch circuit-breaker-api/tests/conftest.py

3.5 环境验证与项目结构图

完成上述步骤后,执行以下命令验证环境是否就绪:

# 1. 确认 Python 版本
python --version
# 输出: Python 3.11.x

# 2. 确认虚拟环境激活
which python
# 输出应包含项目路径下的 venv 或 poetry 虚拟环境路径

# 3. 确认核心依赖已安装
python -c "import fastapi; print(fastapi.__version__)"
python -c "import redis; print(redis.__version__)"

# 4. 确认项目结构
tree -L 3 circuit-breaker-api/

下图展示了催收 API 熔断项目的完整模块依赖关系与数据流向:

催收 API 熔断项目结构图 FastAPI 入口 (main.py) API 路由层 (routes.py) 熔断中间件 (middleware.py) 业务服务层 (services/collection.py) 熔断器核心 (circuit_breaker/) 状态存储 (storage.py / Redis) 模块职责说明 • main.py: 应用启动与路由注册 • routes.py: 催收 API 端点定义 • middleware.py: 请求级熔断拦截 • circuit_breaker/: 熔断状态机 数据流向 请求 → 路由 → 中间件 → 业务 → 熔断器 → 存储/外部系统
环境就绪检查清单:
  1. Python 3.10+ 已安装并可通过命令行调用
  2. 虚拟环境已创建并激活(终端前缀显示 (venv) 或 (circuit-breaker-api))
  3. 核心依赖(fastapi, uvicorn, redis, pybreaker)已安装
  4. 项目目录结构已按上述骨架创建完毕
  5. .gitignore 已配置,排除虚拟环境和缓存文件