这是一个基于 FastAPI 和 Tortoise ORM 的项目,用于实现简单的项目管理功能,包括创建、获取和管理项目。

项目结构

 app/
 │
 ├── api/
 │   └── item.py              # API 路由
 │
 ├── models/
 │   └── item.py              # 数据模型
 │
 ├── services/
 │   └── item_service.py      # 业务逻辑服务
 │
 └── main.py                  # FastAPI 启动文件

环境要求

  • Python 3.7+

  • FastAPI

  • Tortoise-ORM

  • SQLite(或其他数据库)

安装依赖

首先,创建并激活虚拟环境(可选):

 python -m venv venv
 source venv/bin/activate  # Linux/macOS
 venv\Scripts\activate     # Windows

然后安装所需的依赖:

 pip install fastapi tortoise-orm[aiosqlite]

配置与初始化

1. app/models/item.py - 数据模型

在此文件中,我们定义了一个名为 Item 的模型类,该类将映射到 SQLite 数据库中的 item 表。

 from tortoise import fields
 from tortoise.models import Model
 ​
 class Item(Model):
     id = fields.IntField(pk=True)
     name = fields.CharField(max_length=100)
     description = fields.TextField()
 ​
     class Meta:
         table = "item"

2. app/services/item_service.py - 服务层

此文件包含业务逻辑层,用于获取所有项目、根据 ID 获取单个项目以及创建项目。

 from app.models.item import Item
 ​
 # 获取所有项目
 async def get_items():
     return await Item.all()
 ​
 # 根据ID获取项目
 async def get_item_by_id(item_id: int):
     return await Item.get(id=item_id)
 ​
 # 创建新项目
 async def create_item(name: str, description: str):
     return await Item.create(name=name, description=description)

3. app/api/item.py - API 路由

该文件定义了 FastAPI 路由,处理 HTTP 请求并调用相应的服务层方法。

 from fastapi import APIRouter
 from app.services.item_service import get_items, get_item_by_id, create_item
 ​
 router = APIRouter()
 ​
 # 获取所有项目
 @router.get("/items")
 async def get_items_endpoint():
     items = await get_items()
     return [{"id": item.id, "name": item.name, "description": item.description} for item in items]
 ​
 # 根据ID获取单个项目
 @router.get("/items/{item_id}")
 async def get_item_by_id_endpoint(item_id: int):
     item = await get_item_by_id(item_id)
     return {"id": item.id, "name": item.name, "description": item.description}
 ​
 # 创建新项目
 @router.post("/items")
 async def create_item_endpoint(name: str, description: str):
     item = await create_item(name=name, description=description)
     return {"id": item.id, "name": item.name, "description": item.description}

4. app/main.py - FastAPI 启动文件

在这个文件中,我们初始化 FastAPI 应用程序,配置数据库连接,并注册 API 路由。

 from fastapi import FastAPI
 from tortoise import Tortoise
 from app.api import item
 ​
 app = FastAPI()
 ​
 # 启动时初始化数据库连接
 @app.on_event("startup")
 async def startup():
     await Tortoise.init(
         db_url='sqlite://db.sqlite3',  # 使用 SQLite 数据库
         modules={'models': ['app.models.item']}  # 注册模型
     )
     await Tortoise.generate_schemas()  # 生成数据库表
 ​
 # 关闭时关闭数据库连接
 @app.on_event("shutdown")
 async def shutdown():
     await Tortoise.close_connections()
 ​
 # 注册路由
 app.include_router(item.router)

启动与运行

  1. 使用 uvicorn 启动 FastAPI 应用:

 uvicorn app.main:app --reload
  1. 在浏览器中访问以下 API 接口:

  • GET /items: 获取所有项目

  • GET /items/{item_id}: 根据 ID 获取单个项目

  • POST /items: 创建一个新项目,传递 name 和 description 字段