1. 项目结构规范
myproject/
├── app/
│ ├── core/ # 核心配置
│ │ ├── config.py # 环境配置
│ │ └── security.py # 安全配置
│ ├── routers/ # 路由模块
│ │ └── users.py # 用户路由
│ ├── models/ # 数据库模型
│ │ └── user.py # 用户模型
│ ├── schemas/ # Pydantic模型
│ │ └── user.py # 用户Schema
│ ├── services/ # 业务逻辑
│ │ └── user.py # 用户服务
│ ├── dependencies.py # 依赖注入
│ └── db/ # 数据库配置
├── tests/ # 测试用例
│ └── test_users.py # 用户测试
├── requirements.txt # 依赖文件
└── main.py # 入口文件
2. 核心代码示例
配置管理 (app/core/config.py)
from pydantic import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
DB_URL: str = "postgresql+asyncpg://user:pass@localhost:5432/db"
JWT_SECRET: str = "secret-key"
class Config:
env_file = ".env"
settings = Settings()
路由示例 (app/routers/users.py)
from fastapi import APIRouter, Depends, HTTPException
from app.services.user import UserService
from app.schemas.user import UserCreate, UserResponse
from app.dependencies import get_db
router = APIRouter(prefix="/users", tags=["users"])
@router.post("/", response_model=UserResponse)
async def create_user(
user: UserCreate,