FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,基于 Python 3.7+ 的类型提示。为了更好地组织 FastAPI 项目,可以采用以下结构化方式:
1. 项目结构示例
以下是一个典型的 FastAPI 项目结构示例:
复制
my_fastapi_project/
│
├── app/ # 应用代码目录
│ ├── __init__.py # 初始化应用
│ ├── main.py # 主入口文件
│ ├── routers/ # 路由模块
│ │ ├── __init__.py
│ │ ├── user.py # 用户相关路由
│ │ ├── product.py # 产品相关路由
│ │ └── ...
│ ├── models/ # 数据模型(如 Pydantic 模型)
│ │ ├── __init__.py
│ │ ├── user.py # 用户模型
│ │ ├── product.py # 产品模型
│ │ └── ...
│ ├── schemas/ # 数据验证模式(Pydantic 模型)
│ │ ├── __init__.py
│ │ ├── user.py # 用户数据验证
│ │ ├── product.py # 产品数据验证
│ │ └── ...
│ ├── crud/ # 数据库操作(CRUD)
│ │ ├── __init__.py
│ │ ├── user.py # 用户数据库操作
│ │ ├── product.py # 产品数据库操作
│ │ └── ...
│ ├── dependencies/ # 依赖项(如中间件、工具函数)
│ │ ├── __init__.py
│ │ ├── auth.py # 认证依赖
│ │ └── ...
│ ├── config.py # 配置文件
│ ├── database.py # 数据库连接
│ └── exceptions.py # 自定义异常处理
│
├── tests/ # 测试代码目录
│ ├── __init__.py
│ ├── test_user.py # 测试用户相关功能
│ ├── test_product.py # 测试产品相关功能
│ └── ...
│
├── .env # 环境变量文件
├── requirements.txt # 依赖包列表
├── Dockerfile # Docker 镜像构建文件(可选)
└── README.md # 项目说明文档
2. 项目结构说明
2.1 app
目录
-
Pythonmain.py
:这是 FastAPI 的主入口文件,用于创建 FastAPI 应用实例并挂载路由。复制
from fastapi import FastAPI from app.routers import user, product app = FastAPI() app.include_router(user.router) app.include_router(product.router)
-
Pythonrouters
子目录:存放各个功能模块的路由代码。每个模块的路由文件定义一组相关的 API 路径操作。复制
# app/routers/user.py from fastapi import APIRouter router = APIRouter() @router.get("/users/") async def get_users(): return {"message": "Get all users"}
-
Pythonmodels
子目录:存放 Pydantic 模型,用于数据验证和序列化。复制
# app/models/user.py from pydantic import BaseModel class User(BaseModel): id: int name: str email: str
-
schemas
子目录:存放数据验证模式,通常与models
相似,但可以用于更复杂的验证逻辑。 -
Pythoncrud
子目录:存放数据库操作代码,封装 CRUD(增删改查)逻辑。复制
# app/crud/user.py def get_user(db, user_id: int): # 数据库查询逻辑 pass
-
Pythondependencies
子目录:存放依赖项,如中间件、工具函数等。复制
# app/dependencies/auth.py from fastapi import Depends, HTTPException def get_current_user(token: str): # 验证 token 的逻辑 pass
-
config.py
:存放项目的配置信息,如数据库连接字符串、密钥等。 -
database.py
:管理数据库连接和会话。 -
exceptions.py
:定义自定义异常处理逻辑。
2.2 tests
目录
存放测试代码,使用 pytest
等测试框架进行单元测试和集成测试。
Python
复制
# tests/test_user.py
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_get_users():
response = client.get("/users/")
assert response.status_code == 200
assert response.json() == {"message": "Get all users"}
2.3 其他文件
-
.env
:存放环境变量,用于配置敏感信息(如数据库密码)。 -
requirements.txt
:列出项目依赖的 Python 包。 -
Dockerfile
:用于构建 Docker 镜像,便于部署。 -
README.md
:项目说明文档,介绍项目结构、运行方式等。
3. 项目组织原则
-
模块化:将功能划分为独立的模块,每个模块负责特定的功能,便于维护和扩展。
-
解耦:将路由、模型、数据库操作、依赖项等分离,减少模块之间的耦合。
-
可重用性:公共逻辑(如工具函数、中间件)放在
dependencies
目录中,便于复用。 -
测试驱动:编写测试代码,确保代码质量。
通过以上结构化方式,可以更好地组织 FastAPI 项目,使其更易于维护和扩展。