从零开始编写Python FastAPI项目

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 目录
  • main.py:这是 FastAPI 的主入口文件,用于创建 FastAPI 应用实例并挂载路由。

    Python

    复制

    from fastapi import FastAPI
    from app.routers import user, product
    
    app = FastAPI()
    
    app.include_router(user.router)
    app.include_router(product.router)
  • routers 子目录:存放各个功能模块的路由代码。每个模块的路由文件定义一组相关的 API 路径操作。

    Python

    复制

    # app/routers/user.py
    from fastapi import APIRouter
    
    router = APIRouter()
    
    @router.get("/users/")
    async def get_users():
        return {"message": "Get all users"}
  • models 子目录:存放 Pydantic 模型,用于数据验证和序列化。

    Python

    复制

    # app/models/user.py
    from pydantic import BaseModel
    
    class User(BaseModel):
        id: int
        name: str
        email: str
  • schemas 子目录:存放数据验证模式,通常与 models 相似,但可以用于更复杂的验证逻辑。

  • crud 子目录:存放数据库操作代码,封装 CRUD(增删改查)逻辑。

    Python

    复制

    # app/crud/user.py
    def get_user(db, user_id: int):
        # 数据库查询逻辑
        pass
  • dependencies 子目录:存放依赖项,如中间件、工具函数等。

    Python

    复制

    # 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 项目,使其更易于维护和扩展。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值