FastAPI 目录结构推荐

环境:openEuler、Windows 11、WSL 2、python 3.12.3、FastAPI

背景:初学FastAPI,对于其框架结构不熟悉,记录

时间:20241031

说明:使用 FastAPI 搭建项目时,合理的目录结构可以帮助你更好地组织代码,使其更易于维护和扩展。

框架结构

my_fastapi_project/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── config.py
│   ├── dependencies.py
│   ├── models/
│   │   ├── __init__.py
│   │   ├── user.py
│   │   ├── item.py
│   │   └── ...
│   ├── schemas/
│   │   ├── __init__.py
│   │   ├── user.py
│   │   ├── item.py
│   │   └── ...
│   ├── crud/
│   │   ├── __init__.py
│   │   ├── user.py
│   │   ├── item.py
│   │   └── ...
│   ├── services/
│   │   ├── __init__.py
│   │   ├── email.py
│   │   ├── authentication.py
│   │   └── ...
│   ├── routers/
│   │   ├── __init__.py
│   │   ├── users.py
│   │   ├── items.py
│   │   └── ...
│   ├── utils/
│   │   ├── __init__.py
│   │   ├── helpers.py
│   │   ├── validators.py
│   │   └── ...
│   ├── tests/
│   │   ├── __init__.py
│   │   ├── test_users.py
│   │   ├── test_items.py
│   │   └── ...
│   └── static/
│       ├── css/
│       ├── js/
│       ├── images/
│       └── ...
├── migrations/
│   ├── alembic.ini
│   ├── env.py
│   ├── script.py.mako
│   └── versions/
├── .env
├── requirements.txt
├── Dockerfile
└── README.md

目录说明

app/:
项目的主目录。
__init__.py: 使 app 成为一个 Python 包。
main.py: 项目的入口点,包含 FastAPI 应用实例和路由注册。
config.py: 配置文件,用于存储环境变量、数据库连接等配置。
dependencies.py: 依赖注入相关的函数或类。
models/:
存放数据库模型定义。
user.py, item.py: 具体的模型文件。
schemas/:
存放 Pydantic 模型(数据验证和序列化)。
user.py, item.py: 具体的数据模式文件。
crud/:
存放 CRUD (Create, Read, Update, Delete) 操作。
user.py, item.py: 具体的 CRUD 文件。
services/:
存放业务逻辑相关的服务。
email.py, authentication.py: 具体的服务文件。
routers/:
存放 API 路由。
users.py, items.py: 具体的路由文件。
utils/:
存放辅助函数和工具类。
helpers.py, validators.py: 具体的工具文件。
tests/:
存放测试代码。
test_users.py, test_items.py: 具体的测试文件。
static/:
存放静态文件,如 CSS、JavaScript 和图片。
migrations/:
存放 Alembic 迁移文件,用于数据库版本控制。
alembic.ini: Alembic 配置文件。
env.py: Alembic 环境脚本。
script.py.mako: Alembic 脚本模板。
versions/: 存放具体的迁移脚本。
.env:
存放环境变量。
requirements.txt:
项目依赖列表。
Dockerfile:
Docker 容器构建文件。
README.md:
项目文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值