FastAPI 开发环境
概述
搭建一个高效的 FastAPI 开发环境是学习和开发的第一步。本章将详细介绍如何在不同操作系统上配置 FastAPI 开发环境,包括 Python 安装、虚拟环境创建、依赖管理和开发工具配置。
🐍 Python 环境准备
检查 Python 版本
FastAPI 需要 Python 3.7 或更高版本,推荐使用 Python 3.8+:
bash
# 检查 Python 版本
python --version
# 或
python3 --version
# 期望输出: Python 3.8+Python 安装
Windows 系统
powershell
# 方法1: 从官网下载
# 访问 https://www.python.org/downloads/
# 下载最新版本的 Python 安装包
# 方法2: 使用 Chocolatey
choco install python
# 方法3: 使用 Microsoft Store
# 搜索 "Python" 并安装
# 验证安装
python --version
pip --versionmacOS 系统
bash
# 方法1: 使用 Homebrew (推荐)
brew install python
# 方法2: 从官网下载
# 访问 https://www.python.org/downloads/
# 验证安装
python3 --version
pip3 --versionLinux 系统
bash
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip python3-venv
# CentOS/RHEL
sudo yum install python3 python3-pip
# Fedora
sudo dnf install python3 python3-pip
# 验证安装
python3 --version
pip3 --version🔧 虚拟环境管理
使用 venv (推荐)
Python 内置的虚拟环境工具:
bash
# 创建虚拟环境
python -m venv fastapi_env
# 激活虚拟环境
# Windows
fastapi_env\Scripts\activate
# macOS/Linux
source fastapi_env/bin/activate
# 确认虚拟环境已激活
# 命令行前缀会显示 (fastapi_env)
which python # 应该指向虚拟环境中的 Python
# 退出虚拟环境
deactivate使用 conda
如果您使用 Anaconda 或 Miniconda:
bash
# 创建环境
conda create -n fastapi_env python=3.9
# 激活环境
conda activate fastapi_env
# 确认环境
conda info --envs
# 退出环境
conda deactivate使用 pipenv
现代化的 Python 依赖管理工具:
bash
# 安装 pipenv
pip install pipenv
# 创建项目目录
mkdir my_fastapi_project
cd my_fastapi_project
# 创建虚拟环境并安装依赖
pipenv install
# 激活环境
pipenv shell
# 安装包
pipenv install fastapi uvicorn
# 查看依赖图
pipenv graph📦 FastAPI 安装
基础安装
bash
# 确保虚拟环境已激活
pip install fastapi
# 安装 ASGI 服务器
pip install "uvicorn[standard]"
# 验证安装
python -c "import fastapi; print(fastapi.__version__)"完整安装(推荐)
bash
# 安装 FastAPI 及常用依赖
pip install "fastapi[all]"
# 这将包含:
# - uvicorn: ASGI 服务器
# - pydantic[email]: 邮箱验证
# - jinja2: 模板引擎
# - python-multipart: 表单和文件上传
# - itsdangerous: 会话支持
# - python-jose[cryptography]: JWT 支持
# - passlib[bcrypt]: 密码哈希
# - aiofiles: 异步文件操作开发依赖
bash
# 安装开发和测试工具
pip install pytest pytest-asyncio httpx
# 代码格式化和检查
pip install black isort flake8 mypy
# API 测试工具
pip install requests📄 依赖管理
requirements.txt
创建和管理项目依赖:
bash
# 生成 requirements.txt
pip freeze > requirements.txt
# 从 requirements.txt 安装
pip install -r requirements.txt示例 requirements.txt 文件:
txt
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic[email]==2.5.0
sqlalchemy==2.0.23
alembic==1.13.1
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
aiofiles==23.2.1
pytest==7.4.3
pytest-asyncio==0.21.1
httpx==0.25.2
black==23.11.0
isort==5.12.0
mypy==1.7.1pyproject.toml (现代方式)
toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-fastapi-app"
version = "0.1.0"
description = "My FastAPI Application"
authors = [{name = "Your Name", email = "your.email@example.com"}]
dependencies = [
"fastapi>=0.104.0",
"uvicorn[standard]>=0.24.0",
"pydantic[email]>=2.5.0",
"sqlalchemy>=2.0.0",
"alembic>=1.13.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.4.0",
"pytest-asyncio>=0.21.0",
"httpx>=0.25.0",
"black>=23.11.0",
"isort>=5.12.0",
"mypy>=1.7.0",
]
[tool.black]
line-length = 88
target-version = ['py38']
[tool.isort]
profile = "black"
multi_line_output = 3
[tool.mypy]
python_version = "3.8"
warn_return_any = true
warn_unused_configs = true🛠️ 开发工具配置
VS Code 设置
创建 .vscode/settings.json:
json
{
"python.defaultInterpreterPath": "./fastapi_env/bin/python",
"python.formatting.provider": "black",
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.linting.mypyEnabled": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
"files.associations": {
"*.py": "python"
}
}推荐的 VS Code 扩展:
json
// .vscode/extensions.json
{
"recommendations": [
"ms-python.python",
"ms-python.vscode-pylance",
"ms-python.black-formatter",
"ms-python.isort",
"ms-python.mypy-type-checker",
"ms-python.flake8",
"humao.rest-client"
]
}PyCharm 设置
配置 Python 解释器:
- File → Settings → Project → Python Interpreter
- 选择虚拟环境中的 Python 解释器
代码格式化:
- File → Settings → Tools → External Tools
- 添加 Black 格式化工具
类型检查:
- File → Settings → Editor → Inspections
- 启用 Python 类型检查
Git 配置
创建 .gitignore 文件:
gitignore
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
fastapi_env/
# FastAPI
.env
.env.local
.env.production
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Testing
.pytest_cache/
.coverage
htmlcov/
# Database
*.db
*.sqlite3
# Logs
*.log
logs/🚀 项目结构初始化
创建基础项目结构
bash
mkdir my_fastapi_project
cd my_fastapi_project
# 创建目录结构
mkdir -p {app,tests,docs,scripts}
mkdir -p app/{api,core,db,models,schemas,services}
mkdir -p app/api/v1
# 创建基础文件
touch app/__init__.py
touch app/main.py
touch app/core/__init__.py
touch app/core/config.py
touch app/api/__init__.py
touch app/api/v1/__init__.py
touch tests/__init__.py
touch tests/test_main.py
touch README.md
touch requirements.txt
touch .env
touch .gitignore项目结构说明
my_fastapi_project/
├── app/ # 应用代码
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口
│ ├── api/ # API 路由
│ │ ├── __init__.py
│ │ └── v1/ # API v1 版本
│ │ ├── __init__.py
│ │ ├── endpoints/ # 路由端点
│ │ └── api.py # API 路由汇总
│ ├── core/ # 核心配置
│ │ ├── __init__.py
│ │ ├── config.py # 配置文件
│ │ └── security.py # 安全相关
│ ├── db/ # 数据库
│ │ ├── __init__.py
│ │ ├── database.py # 数据库连接
│ │ └── base.py # 数据库基类
│ ├── models/ # 数据库模型
│ │ └── __init__.py
│ ├── schemas/ # Pydantic 模型
│ │ └── __init__.py
│ └── services/ # 业务逻辑
│ └── __init__.py
├── tests/ # 测试代码
│ ├── __init__.py
│ └── test_main.py
├── docs/ # 文档
├── scripts/ # 脚本
├── requirements.txt # 依赖列表
├── .env # 环境变量
├── .gitignore # Git 忽略文件
└── README.md # 项目说明🔧 环境变量配置
创建 .env 文件
bash
# .env
# 应用配置
APP_NAME="My FastAPI App"
APP_VERSION="0.1.0"
DEBUG=True
SECRET_KEY="your-secret-key-here"
# 服务器配置
HOST=0.0.0.0
PORT=8000
# 数据库配置
DATABASE_URL="sqlite:///./app.db"
# DATABASE_URL="postgresql://user:pass@localhost:5432/dbname"
# Redis 配置
REDIS_URL="redis://localhost:6379"
# 日志配置
LOG_LEVEL=INFO
# CORS 配置
ALLOWED_ORIGINS=["http://localhost:3000", "http://localhost:8080"]配置管理代码
创建 app/core/config.py:
python
from typing import List, Optional
from pydantic import BaseSettings, validator
class Settings(BaseSettings):
# 应用配置
app_name: str = "FastAPI App"
app_version: str = "0.1.0"
debug: bool = False
secret_key: str
# 服务器配置
host: str = "0.0.0.0"
port: int = 8000
# 数据库配置
database_url: str
# Redis 配置
redis_url: Optional[str] = None
# CORS 配置
allowed_origins: List[str] = []
@validator("allowed_origins", pre=True)
def assemble_cors_origins(cls, v):
if isinstance(v, str):
return [origin.strip() for origin in v.split(",")]
return v
class Config:
env_file = ".env"
case_sensitive = False
# 创建全局设置实例
settings = Settings()✅ 环境验证
创建测试应用
创建 app/main.py:
python
from fastapi import FastAPI
from app.core.config import settings
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
debug=settings.debug
)
@app.get("/")
async def root():
return {
"message": "Hello FastAPI!",
"app_name": settings.app_name,
"version": settings.app_version
}
@app.get("/health")
async def health_check():
return {"status": "healthy"}运行应用测试
bash
# 确保虚拟环境已激活
# 进入项目目录
cd my_fastapi_project
# 运行应用
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# 或使用环境变量
uvicorn app.main:app --reload验证安装
bash
# 测试 API 端点
curl http://localhost:8000/
curl http://localhost:8000/health
# 访问交互式文档
# 浏览器打开: http://localhost:8000/docs
# 或: http://localhost:8000/redoc🐳 Docker 环境(可选)
Dockerfile
dockerfile
FROM python:3.9-slim
WORKDIR /app
# 安装系统依赖
RUN apt-get update && apt-get install -y \
gcc \
&& rm -rf /var/lib/apt/lists/*
# 复制依赖文件
COPY requirements.txt .
# 安装 Python 依赖
RUN pip install --no-cache-dir -r requirements.txt
# 复制应用代码
COPY ./app /app/app
# 暴露端口
EXPOSE 8000
# 启动命令
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]docker-compose.yml
yaml
version: '3.8'
services:
web:
build: .
ports:
- "8000:8000"
volumes:
- ./app:/app/app
environment:
- DEBUG=True
- DATABASE_URL=postgresql://user:pass@db:5432/fastapi_db
depends_on:
- db
- redis
db:
image: postgres:13
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: fastapi_db
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
postgres_data:📋 开发流程
日常开发命令
bash
# 激活虚拟环境
source fastapi_env/bin/activate # Linux/macOS
# fastapi_env\Scripts\activate # Windows
# 启动开发服务器
uvicorn app.main:app --reload
# 运行测试
pytest
# 代码格式化
black app/ tests/
isort app/ tests/
# 类型检查
mypy app/
# 代码质量检查
flake8 app/ tests/开发脚本
创建 scripts/dev.sh:
bash
#!/bin/bash
set -e
echo "Starting FastAPI development environment..."
# 检查虚拟环境
if [[ "$VIRTUAL_ENV" == "" ]]; then
echo "Please activate virtual environment first"
exit 1
fi
# 安装依赖
pip install -r requirements.txt
# 运行代码检查
echo "Running code quality checks..."
black --check app/ tests/
isort --check-only app/ tests/
flake8 app/ tests/
mypy app/
# 运行测试
echo "Running tests..."
pytest
# 启动开发服务器
echo "Starting development server..."
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000🔍 故障排除
常见问题
1. Python 版本不兼容
bash
# 错误: ModuleNotFoundError
# 解决: 检查 Python 版本
python --version
# 确保使用 Python 3.7+
# 如果有多个版本,明确指定
python3.9 -m venv fastapi_env2. 虚拟环境问题
bash
# 错误: 无法激活虚拟环境
# 解决: 重新创建虚拟环境
rm -rf fastapi_env
python -m venv fastapi_env
source fastapi_env/bin/activate3. 依赖安装失败
bash
# 错误: 编译错误
# 解决: 安装系统依赖
# Ubuntu/Debian
sudo apt-get install python3-dev build-essential
# macOS
xcode-select --install
# 升级 pip
pip install --upgrade pip setuptools wheel4. 端口占用
bash
# 错误: Address already in use
# 解决: 查找并杀死占用进程
lsof -i :8000
kill -9 <PID>
# 或使用不同端口
uvicorn app.main:app --port 8001总结
本章我们完成了 FastAPI 开发环境的完整搭建,包括:
- ✅ Python 环境安装和配置
- ✅ 虚拟环境创建和管理
- ✅ FastAPI 及相关依赖安装
- ✅ 开发工具配置和优化
- ✅ 项目结构初始化
- ✅ 环境变量和配置管理
- ✅ Docker 容器化部署
现在您已经拥有了一个功能完整的 FastAPI 开发环境,可以开始构建您的第一个 FastAPI 应用了!
环境管理建议
- 始终使用虚拟环境进行开发
- 定期更新依赖包版本
- 使用代码格式化工具保持代码风格一致
- 配置 IDE 以获得最佳开发体验
在下一章中,我们将创建第一个 FastAPI 应用,体验 FastAPI 的强大功能。